Printing addresses of an array of elements of an array of C and C ++, why different output?

Possible duplicate:
How to simulate the% printf format when using std :: cout?

I am trying to print the memory addresses of array elements 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 do the same in C ++:

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

I got this conclusion:

P

to




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

+4
source share
4 answers

Pass the void* address before printing, in C ++ the operator<< from ostream overloaded for (const) char* so that it considers it to be 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 my answer .

+8
source

The &array[i] is char* , so cout<< thinks you want to print a string.

+1
source

std::cout does not necessarily treat pointers as pointers. For example, a char* pointer could be a string . Taking the address of an element in a char array basically prints a substring from that point.

+1
source

You must overlay &array[i] on void*

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

This is because C ++ streams work differently for different types. For example, when you pass char* , your data is treated as a C-string, so it prints as a list of characters.

You must explicitly tell C ++ that you want to print the address by casting.

By the way, (void*) not the best way to do this, since you should avoid C-like casting. Always use C ++ style casting ( static_cast , dynamic_cast , reinterpret_cast ). In this case, static_cast will complete the task.

0
source

All Articles