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

后端 未结 2 1244
被撕碎了的回忆
被撕碎了的回忆 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:36

    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;
    

提交回复
热议问题