我假设如果将长变量var初始化为0,则每个字节的值都应为0。(与__int128相同)
这是一段测试代码:
int64_t i64 = { 0 };
auto addr = &i64;
LOG(INFO) << "i64 address=" << addr << ": " << i64;
for (int i = 0; i < sizeof(i64); i++) {
LOG(INFO) << addr + i << ": byte=" << (int)*reinterpret_cast<int8_t*>(addr + i);
}
我希望每个字节都看到全0。但是,事实并非如此,这是通过在带有clang的“ Mac Mojave 10.14.6”上运行
Apple clang版本11.0.0(clang-1100.0.33.12)目标: x86_64-apple-darwin18.7.0线程模型:posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
I1113 23:26:05.741184 103323072 TestCommon.cpp:498] i64地址= 0x7ffeeb589a90:0
I1113 23:26:05.741191 103323072 TestCommon.cpp:500] 0x7ffeeb589a90:字节= 0
I1113 23:26:05.741196 103323072 TestCommon.cpp:500] 0x7ffeeb589a98:字节= 0
I1113 23:26:05.741201 103323072 TestCommon.cpp:500] 0x7ffeeb589aa0:字节= 0
I1113 23:26:05.741205 103323072 TestCommon.cpp:500] 0x7ffeeb589aa8:字节= 1
I1113 23:26:05.741210 103323072 TestCommon.cpp:500] 0x7ffeeb589ab0:字节= 0
I1113 23:26:05.741214 103323072 TestCommon.cpp:500] 0x7ffeeb589ab8:字节= -126
I1113 23:26:05.741219 103323072 TestCommon.cpp:500] 0x7ffeeb589ac0:字节= 96
I1113 23:26:05.741223 103323072 TestCommon.cpp:500] 0x7ffeeb589ac8:byte = 1
这可能是什么原因?它与内存顺序或CPU缓存同步有关吗?还是这些是0字节长的合法字节值?
但是,如果我使用联合来包装它,我可以看到所有字节的值都为零:
union U {
int128_t a;
int8_t b[16];
};
U u = { 0 };
LOG(INFO) << "value=" << *reinterpret_cast<int64_t*>(u.b + 8);
for (int i = 0; i < 16; i++) {
LOG(INFO) << "byte=" << (int)u.b[i];
}
输出:
I1113 23:26:05.757899 103323072 TestCommon.cpp:539]值= 0
I1113 23:26:05.757905 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757910 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757915 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757920 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757925 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757928 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757932 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757936 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757942 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757946 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757951 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757956 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757959 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757966 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757970 103323072 TestCommon.cpp:541]字节= 0
I1113 23:26:05.757975 103323072 TestCommon.cpp:541]字节= 0
赞赏任何见解和投入...
答案 0 :(得分:3)
您的问题是:
auto addr = &i64;
创建:
int64_t* addr = &i64;
因此,每次您增加addr
,它就会增加sizeof int64_t
。
您想要更多类似的东西:
uint8_t* addr = reinterpret_cast<uint8_t*>(&i64);