Question

Why doesn't the rest of the char array get printed out? Given the following code:

char charArray[10];     
charArray[0] = 'a';
charArray[1] = 'b';
charArray[2] = 'c';
charArray[3] = 'd';

string str1 = charArray + string("string") ;
cout << str1;

Output: abcdstring

While this one:

char charArray[10];     
charArray[0] = 'a';
charArray[1] = 'b';
charArray[2] = 'c';

string str1 = charArray + string("string") ;
cout << str1;

Output: abcstring

I understand that the values in the rest of the array indices are unitialized, but there still are values. So I was expecting random characters to show up there, instead, but I'm not seeing any weird characters which signify uninitialized values.

So, why doesn't the rest of the char array get printed out? (Deeper answers with reference to more hardcore stuffs are welcome and greatly appreciated as I'm looking to expand my C++ knowledge to that of an expert.)

Was it helpful?

Solution

Pure luck.

When you use your character array this context

string str1 = charArray + string("string")

the array is interpreted as a C-style string.

C-style strings are terminated by zero character value. In your case the first uninitialized array element (i.e. charArray[4] in the first experiment) just happened to be zero by pure luck (assuming this is a local array). That accidental zero in charArray[4] worked as zero-terminator for the string, so your charArray happened to stand for a valid C-string "abcd". That's exactly what you see.

The same thing happens in the second experiment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top