2013年百度笔试题第8题
下面代码在i386系列PC中输出是什么:
1 typedef struct st{ 2 int xxx; 3 short* yyy; 4 char ccc[32]; 5 }pst; 6 7 int main(void){ 8 pst ppp[16]; 9 char* p = (char*)(ppp[2].ccc+32); 10 printf("%d\n",(p-(char*)(ppp))); 11 }
分析:求的是什么? p是一个地址,ppp也是一个地址,两者相减,明显求的是偏移量。
现在先来看看sizeof(pst)的值,在i386系列PC下,int、指针都是4字节,所以sizeof(pst)=40,那p所指的位置在哪里呢?
(char*)(ppp)=sizeof(pst)*2+sizeof(int)+sizeof(short*)+32 + p
偏移量 + 基址
由上面分析可得,答案是(4+4+32)*2+4+4+32=120
扩散一下:如果是在64位系统下呢? 只要考虑64位下int是4字节(要考虑对齐),指针是8字节,char还是1字节就可以得到答案是(8+8+32)*2+8+8+32 =48*3 =144
浙公网安备 33010602011771号