我正在网站上对C进行练习测试,我碰巧看到了这个问题。 我的疑问在评论中有解释,所以请阅读它们。
#include<stdio.h>
int main()
{
int arr[3] = {2, 3, 4}; // its assumed to be stored in little-endian i.e;
// 2 = 00000010 00000000 00000000 00000000
// 3 = 00000011 00000000 00000000 00000000
// 4 = 00000100 00000000 00000000 00000000
char *p;
p = arr;
p = (char*)((int*)(p));
printf("%d ", *p);
p = (int*)(p+1); // This casting is expected to convert char pointer p
// to an int pointer , thus value at p ,now is assumed
// to be equal to 00000000 00000000 00000000 00000011
// but, the output was : 0 . As ,per my assumption it
// should be : 2^24+2^25 = 50331648 ,Please Clarify
// if my assumption is Wrong and explain Why?
printf("%d\n", *p);
return 0;
}
答案 0 :(得分:2)
如果您要将p
投回int*
,那么int
值将为:
00000000 00000000 00000000 00000011
其中最后一个字节是第二个数组元素的第一个字节。通过执行p+1
,您将跳过第一个元素的最不重要的字节。
请记住,p
仍然是一个字符指针,因此为其分配int*
不会改变它的类型。
当printf
p+1
处的字符时,您正在打印第二个字节的值,即0。
答案 1 :(得分:1)
请记住p
仍然是char
- 指针。因此*p
从中获取char
值。当char
值作为参数传递给可变参数函数(如int
)时,printf
值将被提升为{{1}}。
答案 2 :(得分:1)
p = (char*)((int*)(p));
// till now the pointer p is type casted to store the variable of type character.
printf("%d, ", *p); // %d means integer value so value at first address i.e. 2 will be printed.
p = (int*)(p+1); // here p is still of type character as type casted in step 1 so p(i.e address) and plus 1 will increase only by one byte so
假设整数需要2个字节的存储空间 整数数组将作为
存储在内存中value 2 3 4
address 00000010 00000000 00000011 00000000 00000100 00000000
pointer p+1
所以p+1
指向未填充的位置,因为初始化期间2,3,4存储在整数类型的变量(2个字节)中。
因此p+1
将指向00000000
。
(int*)p+1 // p+1 is type casted again to integer
printf("%d", *p); // this will print 0 as output as by default integer contains 0 as value.