c++ - 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
}
解决方案
在这类问题中处理大量乘法和括号时,重要的是要考虑运算符的优先级。它输出 3 的原因是因为您的程序读取
*(x[0][0])[0][1]
作为
*((x[0][0])[0][1])
因此,您可以看到在此它取消引用整个事物,而不仅仅是(x[0][0])
推荐阅读
- python - boost-python 嵌套命名空间导出代码中的错误
- elasticsearch - 删除 ElasticSearch 中的读写索引后如何回收磁盘空间?
- python - 基于子字符串的字典计数
- nlog - 如何让 Fluentd 写入日志文件
- javascript - 条件时Joi多个
- docker - Elasticbeanstalk 部署失败
- google-cloud-ml - P100 和 K80 之间的 Cloud ML-Engine 配额
- kotlin-coroutines - 如何在同一个协程中的动态代理中继续挂起功能?
- rest - WSO2 API 管理器返回二进制响应
- c++ - 为什么使用指针交换数字(初学者)?