从(char *)到(int *)的引用解引用在此示例中未被理解

我正在网站上对C进行练习测试,我碰巧看到了这个问题。 我的疑问在评论中有解释,所以请阅读它们。

#include int main() { int arr[3] = {2, 3, 4}; // its assumed to be stored in little-endian ie; // 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; } 

如果你将pint* ,那么int值将是:

 00000000 00000000 00000000 00000011 

其中最后一个字节是第二个数组元素的第一个字节。 通过执行p+1 ,您将跳过第一个元素的最不重要的字节。

请记住, p仍然是一个char指针,因此为它指定一个int*不会改变它的类型。

当您在p+1处打印char时,将打印第二个字节的值,即0。

 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 ie 2 will be printed. p = (int*)(p+1); // here p is still of type character as type casted in step 1 so p(ie 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.

记住p仍然是一个char -pointer。 所以*p从中获取char值。 然后,当作为参数传递给可变参数函数(如printf )时, char值将被提升为int