How does cout work with a given array?

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

If I have this code:

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

He gives me this result:

abc

However, if I have this code:

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

He gives me this result:

0x28ff30

Why doesn't he print 123?

+3
source share
6 answers

, , , const char *, C. , , . , , , undefined.

int int * , const void * . const void * cout , , , .

, !

+15

myArray cout << myArray;, . operator<<, char* , ; , , . , .

char , , , , undefined, "".

+1

operator <<, basic_ostream (, cout) const char* .

const int* ( const int[]) . , .

, .

, , , basic_ostream::operator<<(const void*), .

+1

std:: cout - std:: ostream, .

:

std::ostream& operator << (std::ostream&, char*);

std:: cout < < somevar; . , - ( -/ / ..).

++ Overload Resolution

+1

ints; int. , , . , , ( ).

, , , , , NUL (\0), , . , NUL, abc .

0

Since it does not know that your array is an array or what data is in it. When you execute cout << myArray, "myArray" is treated as a type of pointer that can point to something. Therefore, instead of trying to dereference the pointer (and potentially crash the application if the pointer has not been initialized), the address pointed to by the pointer will be printed.

0
source

All Articles