3
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 ?

JBentley
  • 6,099
  • 5
  • 37
  • 72

3 Answers3

4

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.

KBi
  • 383
  • 1
  • 7
-3

Q: How can it Print USA when a is character array of length 3 and there is no for memory '\0' ?

Simply print all characters that are in the array.

for example

for ( char c : a ) std::cout << c;
std::cout << std::endl;

In this case the terminating zero is not required.

If your compiler does not support the range based for statement then you can use an ordinary loop:

for ( size_t i = 0; i < sizeof( a ); i++ ) std::cout << a[i];
std::cout << std::endl;

Or indeed you can use member function write

std::cout.write( a, sizeof( a ) );

If you will print it the following way

std::cout << a;

then the program will have undefined behaviour. There is no guarantee that after the array there will be a zero byte in the memory.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-4

Insert terminator:

char a[4]={'U','S','A', '\0' };

lsalamon
  • 7,998
  • 6
  • 50
  • 63