期间,C / C ++编译时解析地址偏移? [英] Are address offsets resolved during compile time in C/C++?
本文介绍了期间,C / C ++编译时解析地址偏移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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));
时手动偏移被在编译时解决或不会添加在运行时进行算术运算的开销?
Is the manual offset being resolved at compile time or does it add overhead of performing arithmetic operations during runtime?
推荐答案
即使你有一个恒定的,而不是的sizeof(INT)
,编译器不能提前知道地址在 p
,所以它必须做加法。如果你有类似 I = sizeof的(INT)+4
那么就应该做了优化编译时和直接设置 I
到 8
。
Even if you have a constant instead of sizeof(int)
, compiler cannot know in advance the address in p
, so it will have to do the addition. If you have something like i = sizeof(int)+4
then it should do the optimization compile time and directly set i
to 8
.
另外,我觉得当你做的:
Also, I think when you do:
*((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 ++编译时解析地址偏移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文