首页 > 解决方案 > C++ 解引用指针。为什么会发生这种变化?

问题描述

我很难理解为什么将 * 放在括号外最终会改变值。我明白为什么 2 会打印出来,但我不明白为什么 3 会打印出来。任何帮助将不胜感激,谢谢。

int main()
{
     //delcaring typedef of boxes
     typedef int boxes[2][2];

     //delcaring variables that are going to be placed into the boxes
     int a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8;

     //declaring two boxes variables and storing variables
     boxes myBox={{a,b},{c,d}};
     boxes myBox2={{e,f},{g,h}};

     //placing those boxes into a pointer boxes array
     boxes *x[2][2]={{&myBox,&myBox2,},{&myBox,&myBox2}};

    //testing code
    cout<<(*x[0][0])[0][1]<<endl;  //prints out 2
    cout<<*(x[0][0])[0][1]<<endl;  //prints out 3

}

标签: c++pointers

解决方案


在这类问题中处理大量乘法和括号时,重要的是要考虑运算符的优先级。它输出 3 的原因是因为您的程序读取

*(x[0][0])[0][1]

作为

*((x[0][0])[0][1])

因此,您可以看到在此它取消引用整个事物,而不仅仅是(x[0][0])


推荐阅读