如何使用std :: cout模拟printf的%p格式? [英] How to simulate printf's %p format when using std::cout?
问题描述
unsigned char *teta = ....;
...
printf("data at %p\n", teta); // prints 0xXXXXXXXX
如何使用 iostream
s?是否有 std ::
?特征像 std :: hex
来做这种转换(地址 - >字符串),所以 std :: cout< std :: ??? << teta < std :: endl
会打印该地址吗?
How can I print variable address using iostream
s? Is there a std::
??? feature like std::hex
to do this kind of conversion (address -> string), so std::cout << std::??? << teta << std::endl
will print that address?
(没有sprintf的,请;))
(no sprintf's, please ;))
推荐答案
投入 void *
:
unsigned char* teta = ....;
std::cout << "data at " << static_cast<void*>(teta) << "\n";
iostreams通常假设你有一个字符串 char *
指针,但是 void *
指针只是一个地址(简化),所以iostreams不能做任何事情,除了将该地址转换为字符串,而不是该地址的内容。
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.
这篇关于如何使用std :: cout模拟printf的%p格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!