首页 > 解决方案 > c++ 指针分段的混淆

问题描述

#include<iostream>

using namespace std;

int main(){

  int x = 5;
  int y[4] = {0,9,3,1};
  int *add_x = &y[2];


  cout << y[1] << endl;      /*1st output*/

  cout << sizeof(x) << endl;  /* 2nd output*/
  cout << add_x << endl;       /* 0x7fff20d9b1d8*/  /*3rd output*/

  cout << &add_x << endl;      /* 0x7fff20d9b1c8*/  /*4th output*/
  cout << &add_x[0] << endl;   /* 0x7fff20d9b1d8*/  /*5th output*/
  cout << &add_x[1] << endl;   /* 0x7fff20d9b1dc*/
  cout << &add_x[2] << endl;

  cout << &y[2] << endl;       /* 0x7fff20d9b1d8 */


}

大家好,我只是想知道这里代码中的第 3、第 4 和第 5 个输出有什么区别?

我知道第三个输出是地址y[2](因为这是我定义*add_xwhich 是指向的指针的方式y[2]),但是怎么样&add_x(我知道这是add_x指针的地址)。

这里的&add_x[0], &add_x[1],是什么&add_x[2]

因为&add_x是我认为的指针的地址,所以当我在 [0],[1],[2] 之后放入时&add_x,它给了我一些似乎是地址的东西。那么究竟是什么&add_x[0]&add_x[1]

add_x和(即第三和第五输出)之间究竟有什么区别&add_x[0],它们应该是相同的吗?因为“cout”的输出是一样的。

标签: c++

解决方案


推荐阅读