Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing array element memory adresses C and C++, why different output? [duplicate]

Possible Duplicate:
How to simulate printf's %p format when using std::cout?

I try to print out the array element memory addresses in C and C++.

In C:

char array[10];
int i;
for(i =0; i<10;i++){
    printf(" %p \n", &array[i]);
}

I got the memory addresses: 0xbfbe3312, 0xbfbe3313, 0xbfbe3314, ....

But if I try to make the same in C++:

char array[10];
for(int i =0; i<10;i++){
    std::cout<<&array[i]<<std::endl;
}

I got this output:

P��
��

k�



Why is it different? Should I use the cout differently in C++ to print out the memory addresses? How should I print out the memory addresses?

like image 479
W3ctor Avatar asked Dec 09 '22 08:12

W3ctor


1 Answers

Cast the address to void* before printing, in C++ the operator<< of ostream is overloaded for (const) char* so that it thinks it's a c-style string:

char array[10];
for(int i =0; i<10;i++){
    std::cout << static_cast<void*>(&array[i]) << std::endl;
}

Also see this answer of mine.

like image 105
Xeo Avatar answered Dec 25 '22 23:12

Xeo