Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does cout work when given an array? [duplicate]

Tags:

c++

cout

Possible Duplicate:
Why does cout print char arrays differently from other arrays?

If I have this code:

char myArray[] = { 'a', 'b', 'c' };
cout << myArray;

It gives me this output:

abc

However, if I have this code:

int myArray[] = { 1, 2, 3 };
cout << myArray;

It gives me this output:

0x28ff30

Why does it not print out 123?

like image 713
John Smith Avatar asked Nov 29 '22 17:11

John Smith


2 Answers

The reason that the first piece of code works is that the compiler is implicitly converting the array into a const char * character pointer, which it's then interpreting as a C-style string. Interestingly, this code is not safe because your array of characters is not explicitly null-terminated. Printing it will thus start reading and printing characters until you coincidentally find a null byte, which results in undefined behavior.

In the second case, the compiler is taking the int array and implicitly converting it into an int * pointer to the first element, then from there to a const void * pointer to the first element. Printing a const void * pointer with cout just prints its address, hence the output you're getting.

Hope this helps!

like image 93
templatetypedef Avatar answered Dec 16 '22 00:12

templatetypedef


There is an operator << that knows about basic_ostream instances (such as cout) on the left-hand-side and const char*s on the right.

There is no such operator defined for const int* (or const int[]). Although you are perfectly at liberty to create one.

Just be sure to specify a sentinel at the end of your arrays to prevent running off the end of your buffer.

The reason you see the pointer value is because there is an basic_ostream::operator<<(const void*) which will print this.

like image 37
Johnsyweb Avatar answered Dec 15 '22 22:12

Johnsyweb