Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ String Size Error

char a[3]={'U','S','A'};
cout<<a;

How can it Print USA when a is character array of length 3 and there is no for memory '\0' ?
Where will be '\0' stored ?

like image 726
user3416701 Avatar asked Sep 18 '26 10:09

user3416701


1 Answers

cout will print until it encounters a \0.

Now if it happens to be that in the physical memory, the byte next to your array has the value 0, cout will take it as the terminator. It can happen as the next byte may have any garbage value, including 0.

However, there is no guarantee what will be next to your array's boundary. In one case you have found 0 does not mean it will continue for other cases too. The actual outcome is undefined behaviour, which, in this particular case, matched with the expected behaviour of cout in case the array was null-terminated.

like image 172
KBi Avatar answered Sep 19 '26 23:09

KBi