c++ - C/C++ 中的地址偏移量是否在编译时解析?

标签 c++ c memory offset resolve

void *p = malloc(1000);
*((int*)p) = 666;
*((int*)p+sizeof(int)) = 777;
int i;
for (i = 0; i<10; ++i)
    printf("%d ", *((int*)p+sizeof(int)*i));

手动偏移量是在编译时解决的还是会增加运行时执行算术运算的开销?

最佳答案

即使你有一个常量而不是sizeof(int),编译器也无法提前知道p中的地址,所以它必须进行加法。如果您有类似 i = sizeof(int)+4 的内容,那么它应该优化编译时间并直接将 i 设置为 8

另外,我认为当你这样做时:

*((int*)p+sizeof(int)) = 777;

你的意思是:

*((int*)p + 1) = 777; /* or ((int*)p)[1] = 777; */

类似地,printf("%d ", *((int*)p+sizeof(int)*i)); 应该是:

printf("%d ", *((int*)p + i));

关于c++ - C/C++ 中的地址偏移量是否在编译时解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11491191/

相关文章:

c - 为什么我们将字符串存储在字符指针中,例如 fopen(); 中?

c - 此代码如何将指针对齐到 64 位边界?

performance - 使用 'static vs ' a 有什么性能差异?

c++ - 使用 Cmake 来做 ./genMakefiles && make -j4

C++运算符==和隐式转换解析

c++ - 无法在 Windows 7 中执行 makefile

c - 在 C 中进行二进制算术的最佳方法?

c++ - 一个简单的win32多线程代码。这行得通吗?

linux - mmap/dev/mem时的缓存和 volatile 内存

c++ - 虚拟表和 _vptr 存储方案