I’m using the 2D character arrays for storing multiple strings. The code below works fine & outputs the proper strings.
char str[3][4];
std::cin >> str[0] >> str[1] >> str[2] >> str[3];
std::cout << str[0] << '\n' << str[1] << '\n' << str[2] << '\n' << str[3];
but when I try this
char str[3][3];
std::cin >> str[0] >> str[1] >> str[2];
std::cout << str[0] << '\n' << str[1] << '\n' << str[2];
Then, if I input
abc
xyz
pqr
I get the output
abcxyzpqr
xyzpqr
pqr
What might be the possible explanation?
It’s because you’re allocating 3
chars per string and they are of length 3 – so there’s no\0at the end of the string. C++ strings should end with a\0to mark the end. When 4chars are allocated, C++ automatically pads each string with a\0. It’s safe to create arrays of at leastn+1chars when you need to store at mostnchars in that.It seems that the total 9
chars ofstrare contiguous, so the first string is of length 9. Thecoutstatement goes to print fromstr[0][0], and as there’s no\0at the end ofstr[0], it continues printingstr[1]andstr[2].