c++ - 将指针转换为指向多维数组的指针
问题描述
是否可以将const int *const p
维度 A B C 的一维指针转换为指向大小为多维数组的指针[A][B][C]
?
解决方案
这是一个如何执行此操作的示例。关键是使用 typedef 来设置指向指针数组的指针,这样你就不会太困惑了。
typedef int (*pint3)[A][B];
在这一行中,我们设置了一个指向 int 指针的二维数组的类型。二维数组的维度等于您最初考虑的维度中的两个。
正如评论中提到的,这种方法违反了别名。这种类型的指针重新分配容易出错,应该避免。
#include <iostream>
int main() {
int A = 2;
int B = 2;
int C = 3;
int array[]{1, 1, 1, 1, 2, 2, 2,2, 3,3,3,3};
const int *const p = array;
typedef int (*pint3)[A][B];
auto threeDArray = (pint3) p;
std::cout << "Printing 3D array: " << std::endl;
for(int i = 0; i < C; i++ ) {
for(int j = 0; j < B; j++) {
for (int k = 0; k < A; k++) {
std::cout << threeDArray[i][j][k];
}
std::cout << std::endl;
}
std::cout << std::endl;
}
}
输出:
Printing array:
11
11
22
22
33
33
Process finished with exit code 0
推荐阅读
- python - 将 Azure Web 应用连接到 Azure Redis 缓存
- css - 仅在 IOS 中以字体显示的奇怪空间 - 是什么触发了这个?
- c# - 如何将 DataGridViewCellEventArgs 设置为已处理?
- mysql - 测试相互双边一对一连接
- python - 防止动画按钮在 on_press 或 on_release 上改变颜色(无 kv / Python 部分)
- python - OpenCV 无法在 init.py 中找到 cv2.Face 来分配识别器
- c# - 泛型作为参数,我做错了什么?
- ubuntu - 如何检查正在运行的服务的版本?
- javascript - d3 each() .method 这个上下文使用 TypeScript
- python - 如何将光栅文件直接合并到 ENVI 或 LAN