2

我在一个网站上对 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;
 }
4

3 回答 3

2

如果您要p转换回int*,那么int值将是:

00000000 00000000 00000000 00000011

最后一个字节是第二个数组元素的第一个字节。通过这样做p+1,您将跳过第一个元素的最不重要的字节。

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

当您printf使用 char 时p+1,您正在打印第二个字节的值,即 0。

于 2013-04-12T05:29:06.700 回答
1

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

于 2013-04-12T05:32:44.680 回答
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 

sop+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.

于 2013-04-12T05:37:34.427 回答