C++中如何获取指针数组指向的数组的值?
指针数组访问二维数组元素的问题
你的代码问题出在指针访问的优先级和类型匹配上,核心问题拆解如下:
原代码的错误根源
你定义的colorOrder是一个指针数组,每个元素的类型是const int (*)[3]——也就是指向长度为3的int数组的指针。
在循环里写*colorOrder[i][j]时,C++中[]的优先级比*高,这个表达式等价于*(colorOrder[i] + j):
- 当
j=0时,colorOrder[i]+0指向原数组首地址,解引用后能拿到正确的第一个元素 - 但
j=1时,colorOrder[i]+1会跳过一整个int[3]的内存空间,指向原数组之外的未知内存,解引用后得到的就是随机值或错误数据,这就是你看到乱码的原因
修正后的代码
需要先对colorOrder[i]解引用,拿到它指向的int[3]数组,再用下标访问元素,把表达式改成(*colorOrder[i])[j]即可:
#include <iostream> using namespace std; int main() { const int violet[3] = { 128, 0, 256 }; const int springGreen[3] = { 0, 256, 128 }; const int orange[3] = { 256, 128, 0 }; const int (*colorOrder[3])[3] = { &orange, &violet, &springGreen }; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << (*colorOrder[i])[j]; // 修正指针访问逻辑 if (j < 2) { cout << ","; } } cout << "\n"; } }
更直观的简化写法
如果觉得上述指针语法过于繁琐,可以直接用指向int的指针数组存储每个颜色数组的首地址——数组名在多数场景下会隐式转换成指向首元素的指针,代码会更符合直觉:
#include <iostream> using namespace std; int main() { const int violet[3] = { 128, 0, 256 }; const int springGreen[3] = { 0, 256, 128 }; const int orange[3] = { 256, 128, 0 }; const int* colorOrder[3] = { orange, violet, springGreen }; // 简化指针定义 for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << colorOrder[i][j]; // 直接用下标访问即可 if (j < 2) { cout << ","; } } cout << "\n"; } }
内容的提问来源于stack exchange,提问作者SmellydogCoding
相关产品推荐
相关产品推荐

