#include <iostream>
#include <string>
#include <cstring>
int main()
{
using namespace std;
string cppString = "string1";
//size of C++ String
cout << sizeof(cppString) << endl;
cout << cppString << endl;
//To list the corresponding ASCII code for C++ String
for (int index = 0; index < sizeof(cppString); ++index)
std::cout << static_cast<int>(cppString[index]) << " ";
char cString[] = "string2";
//size of C String
cout << "\n" << sizeof(cString) << endl;
cout << cString << endl;
//To list the corresponding ASCII code for C String
for (int index = 0; index < sizeof(cString); ++index)
std::cout << static_cast<int>(cString[index]) << " ";
}
Output:
24
string1
115 116 114 105 110 103 49 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
8
string2
115 116 114 105 110 103 50 0
I am very new to programming. I've tried googling the answer for this, but the explanation available was beyond my scope of understanding.
I am aware of that C String is what is accompanied by null terminator when created and C++ string is not. However, when I test out which ASCII code is saved in memory for both C++ String and C String, it appears that not only does C-String has the null terminator(as expected), but C++ string also ends up with continuous null terminators after ASCII code 49.
In Gaddis book, it stipulates, All of a program’s string literals are stored in memory as C-strings, with the null terminator automatically appended.
Question:
- Following the information of Gaddis book, could it have been that my string literal, "string1", was created as C-String with null terminator at the end, rendering the cppString to behave like C-String, hence the reason why the ASCII code showing those null terminators after 49?