Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing char arrays c++

Tags:

c++

arrays

I was playing around with c strings in c++ and found some behavior I don't understand when I don't terminate a char array.

char strA[2] = {'a','\0'};
char strB[1] = {'b'};
cout << strA << strB;

I would expect this to print ab, but instead it prints aba. If I instead declare strB before strA, it works as expected. Could someone explain what's going on here?

like image 687
conrad12345 Avatar asked Jan 03 '23 09:01

conrad12345


1 Answers

This is undefined behaviour and you simply are lucky that replacing the declaration of these 2 arrays works for you. Let's see what is happening in your code:

char strA[2] = {'a','\0'};

Creates an array that can be treated like a string - it is null terminated.

char strB[1] = {'b'};

Creates an array that cannot be treated like a string, because it lacks the null terminating character '\0'.


std::cout << strA << strB;

The first part, being << strA, works fine. It prints a since strA is treated as a const char*, which provided as an argument for std::ostream& operator << will be used to print every character untill the null terminating character is encountered.

What happens then? Then, the << strB is being executed (actually what happens here is a little different and more complicated than simply dividing this line into two, separate std::cout << calls, but it does not matter here). It is also treated as a const char*, which is expected to ended with mentioned '\0', however it is not...

What does that lead to? You are lucky enough that there randomly is only 1 character before (again - random) '\0' in memory, which stops the (possibly near-infinite) printing process.


Why, if I instead declare strB before strA, it works as expected?

That is because you were lucky enough that the compiler decided to declare your strA just after the strB, thus, when printing the strB, it prints everything that it consists + prints strA, which ends with null terminating character. This is not guaranteed. Avoid using char[] to represent and print strings. Use std::string instead, which takes care of the null terminating character for you.

like image 88
Fureeish Avatar answered Feb 06 '23 10:02

Fureeish