Re: [心得] 晶睿面试考题

楼主: xtxml (赤木巧☠)   2014-10-09 13:18:57
※ 引述《lovesnake (LoyalDog)》之铭言:
: 4. 死在这一题...死不瞑目要把完整题PO上来。
: Run the follow code on 32bit little-endian PC. What is the final result?
: char hello[] = "hello";
: int data[] = {348, 152, 65538, NULL, 32, 222};
: void *p1 = data - 1;
: short *p2 = (short *)p1 + sizeof(hello);
: int *p3 = (int *)((char *)p2 + (char)*p2);
: printf("%d", *p3);
看到这题忽然想闲聊一下。
很显然他是想考byte排列顺序跟指标操作的题目。
不过我比较有疑问的一点就是:
我依稀记得,C/C++的标准下,没有规范数值类型实际的byte数,只规定最小要几个byte。
(只有char固定是1,以及int32_t这类指定长度的数值)
姑且就当int在32-bit系统是4 bytes好了。
好像没有规定32-bit系统下,short一定要2 bytes不能是4 bytes。
只有sizeof(short) <= sizeof(int) <= sizeof(long)这个原则。
所以这样看来short *p2 = (short *)p1 + sizeof(hello);这答案是啥似乎就很难说了。
如果我搞错了什么请鞭小力一点,只是忽然想到闲聊一下XD
作者: elfkiller (没有暱称)   2014-10-10 01:45:00
作者: sipper   2014-10-11 02:02:00
题目中hello不是个array吗? sizeof结果是 5吧?
楼主: xtxml (赤木巧☠)   2014-10-13 12:12:00
sizeof不会错,但p2的实际位置在哪就不一定了附带一提,"hello"的sizeof应该是6

Links booklink

Contact Us: admin [ a t ] ucptt.com