开发者

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

开发者 https://www.devze.com 2023-02-25 14:59 出处:网络
unsigned char *teta = ....; ... printf(\"data at %p\\n\", teta); // prints 0xXXXXXXXX How can I print variable address using iostreams? Is there a std::??? feature like std::he开发者_Python百科x to
unsigned char *teta = ....;
...
printf("data at %p\n", teta); // prints 0xXXXXXXXX

How can I print variable address using iostreams? Is there a std::??? feature like std::he开发者_Python百科x to do this kind of conversion (address -> string), so std::cout << std::??? << teta << std::endl will print that address?

(no sprintf's, please ;))


Cast to void*:

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

iostreams generally assume you have a string with any char* pointer, but a void* pointer is just that - an address (simplified), so the iostreams can't do anything other than transforming that address into a string, and not the content of that address.


Depending on wheter or not you want to use more formatting options printf gives, you could consider using sprintf

By it, you could format a string just like you'd do with printf, and afterwards print it out with std::cout

However, this would involve using a temporary char array so the choice depends.

An 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消