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

后端 未结 2 1243
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 21:00
unsigned char *teta = ....;
...
printf(\"data at %p\\n\", teta); // prints 0xXXXXXXXX

How can I print variable address using iostreams

2条回答
  •  长情又很酷
    2020-12-03 21:33

    Cast to void*:

    unsigned char* teta = ....;
    std::cout << "data at " << static_cast(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.

提交回复
热议问题