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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With