打印 64 位 C++ 完整内存地址 [英] print 64bit c++ full memory address
问题描述
当我在 64 位机器上为 C++ 程序编写代码时,我注意到打印变量的地址(例如)只返回 12 个十六进制字符,而不是 16 个.这是一个示例代码:
While I was writing code on a 64 bit machine for a c++ program,I noticed that printing the address of a variable (for example) returns just 12 hexadecimal characters, instead of 16. Here's an example code:
int a = 3 ;
cout sizeof(&a) << " bytes" << endl ;
cout << &a << endl ;
输出为:
8 个字节
0x7fff007bcce0
0x7fff007bcce0
显然,变量的地址是 8 字节(64 位系统).但是当我打印它时,我只得到 12 个十六进制数字而不是 16 个.
Obviously, the address of a variable is 8 byte (64 bit system). But when I print it, I get only 12 hexadecimal digits instead of 16.
为什么会这样?我认为这是由于 4 个丢失"的事实.数字是未打印的前导零.但这只是我的思想,我希望有一个明确的和技术上正确的回答.
Why this? I think that is due to the fact that the 4 "lost" digits were leading zeroes, that were not printed. But this is only my thought, and I wish to have a definitive and technically correct answer.
如何打印完整地址?有没有内置的解决方案,或者我应该手动使用sizeof"吗?为了得到真正的长度和然后在地址中添加正确数量的零?
How could I print the entire address? Is there a built-in solution, or should I manually use "sizeof" in order to get the real lenght and then add to the address the right number of zeroes?
原谅我,我在谷歌上搜索了一天来回答我愚蠢的问题,但我找不到答案.我只是一个新手.(在 stackoverflow 上,我没有找到关于我需要知道的内容的任何问题/答案,但也许我错了.)
Forgive me, I googled for a day for an answer to my stupid question, but I wasn't able to find an answer. I'm just a newbie. (On stackoverflow I did not find any question/answer about what I needed to know, but maybe I'm wrong.)
推荐答案
有人在这里问了一个非常相似的问题:64 位机器上的 C++ 指针
Someone asks a pretty similar question here: c++ pointer on 64 bit machine
希望这有帮助:)
要打印带前导零的完整 64 位地址,您可以使用:
To print the full 64bit address with leading zeros you can use:
std::cout
<< "0x"
<< std::hex
<< std::noshowbase
<< std::setw(16)
<< std::setfill('0')
<< n
<< std::endl ;
来自:如何在使用 cout << 时用前导零填充 int运算符?
这篇关于打印 64 位 C++ 完整内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!