首页 > 解决方案 > 将指针转换为指向多维数组的指针

问题描述

是否可以将const int *const p维度 A B C 的一维指针转换为指向大小为多维数组的指针[A][B][C]

标签: c++pointers

解决方案


这是一个如何执行此操作的示例。关键是使用 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

推荐阅读