How to simulate printf% p format when using std :: cout?

unsigned char *teta = ....; ... printf("data at %p\n", teta); // prints 0xXXXXXXXX 

How to print the address of a variable using iostream s? Is there a std:: ??? for example, std::hex do this kind of conversion (address → string), so std::cout << std::??? << teta << std::endl std::cout << std::??? << teta << std::endl print this address?

(no sprites, please;))

+17
c ++ gcc iostream
Apr 14 2018-11-11T00:
source share
2 answers

Paste into void* :

 unsigned char* teta = ....; std::cout << "data at " << static_cast<void*>(teta) << "\n"; 

iostreams usually assume that you have a string with any char* pointer, but the void* pointer is exactly that address (simplified), so iostreams cannot do anything except convert this address to a string, not the contents of that address.

+25
Apr 14 2018-11-11T00:
source share
— -

Depending on what you want to use more printf formatting options, you can use sprintf

With it, you can format the string in the same way as with printf, and then print it with std::cout

However, this will be due to the use of a temporary char array, so the choice depends.

Example:

 unsigned char *teta = ....; ... char formatted[ 256 ]; //Caution with the length, there is risk of a buffer overflow sprintf( formatted, "data at %p\n", teta ); std::cout << formatted; 
+1
Apr 14 '11 at 0:15
source share



All Articles