为什么这个程序的输出是2和0?

时间:2017-11-26 17:43:57

标签: c pointers

我收到了意想不到的输出。请告诉我你得到了什么?

代码如下:

#include<stdio.h>

int main()
{
    int arr[3] = {2, 3, 4};
    char *p;
    p = arr;
    p = (char*)((int*)(p));
    printf("%d, ", *p);
    p = (int*)(p+1);
    printf("%d", *p);
    return 0;
  }

输出:

  

2 0

1 个答案:

答案 0 :(得分:1)

int arr[3] = {2, 3, 4}语句将如何存储在memory中? arr本地变量,它将存储在RAM的堆栈部分,假设起始地址为0x100

 arr[0] arr[1] arr[2]
   |--------------------|
   |   2   |  3  |  4   |
   |--------------------|
  0x100     0x104  0x108
  arr 
  p

接下来,p = (char*)((int*)(p));首先p转换为int pointer,然后再转换为char pointer,即p仅指向1st byte

所以当你执行第一个printf

printf("%d, ", *p);

此处pchar pointer,它会将0x100中的数据提取到0x101 2,以便打印2

接下来,当你做

p = (int*)(p+1); // here first p+1 will happen means 0x101 which is converted later into int pointer , but only in this statement(typecasting effect will be in this statement only  .

当您打印下一个printf时,p仍然是char pointer,因此它只会获取1 byte data,而不是4 byte

  printf("%d", *p);// it will print what is the data in 0x101 ? it's 0 check the binary representation of array 

测试用例: 如果p = (int*)(p+1)可以在printf内推出,则会产生不同的结果,例如

printf("%d\n",(int*)(p+1))

我希望它有所帮助。