C++ 二维数组和指针引用

标签 c++ arrays matrix

在下面的代码中,当 arr 被传递给转置函数并检查 a 的内容作为 a[0] 时,它给出 0x00...001但不是为 arr 检查的原始地址,为什么会这样,有什么问题?。我希望 a[0] 是数组中 1 的地址,而 a[0][1] 是数组的第一个元素。请解释。

问题:

int arr[][4] = { { 1, 2, 3, 4},{ 5, 6,7,8 },{ 9,10,11,12 } };
    transpose((int **)arr, 3, 4);
    int** transpose(int** a, int m, int n)
    {
        int** output = new int*[n];
        for (int i = 0;i < m;i++)
        {
            output[i] = new int[n];
        }
        for (int i = 0;i < m;i++)
        {
            for (int j = 0;j < n;j++)
            {
                //*((output[j]) + i) = *(a[i] + j);
                //*((output[j]) + i) = a[i][j];
                output[j][i] = a[i][j];
            }
        }
        return output;
    }

抛出异常。

工作正常:

 int** output=transpose((int *)arr, 3, 4);
    print(output,3,4);
    int**transpose(int * a, int m, int n)
    {
        int** t = new int*[n];
        for (int i = 0;i < n;i++)
        {
            t[i] = new int[m];
        }
        for (int i = 0;i < m;i++)
        {
            for (int j = 0;j < n;j++)
            {
                t[j][i] = *((a + i*n) + j);
            }
        }
        return t;
    }

    void Matrix::print(int ** a, int m, int n)
    {
        for (int i = 0;i < m;i++)
        {
            for (int j = 0;j < n;j++)
            {
                std::cout << a[i][j] << ",";
            }
            std::cout << "\n";
        }
    }

最佳答案

为了使您的代码能够处理二维数组,应如下所示修改代码。

int arr[3][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
transpose(&arr, 3, 4);

int** transpose( int(*a)[3][4], int m, int n)
{
    int** output = new int*[n];
    for (int i = 0; i < m; i++)
    {
        output[i] = new int[n];
    }
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            //*((output[j]) + i) = *(a[i] + j);
            //*((output[j]) + i) = a[i][j];
            if (i < n && j < m )
            {
                output[j][i] = (*a)[i][j];
            }
        }
    }
    return output;

看参数声明int(*a)[3][4] .它说变量 a是指向大小为 [3][4] 的二维数组的指针。附加检查 if (i < n && j < m )确保数组访问不会越界。

它会毫无异常(exception)地工作!

关于C++ 二维数组和指针引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43042145/

相关文章:

C++ - 为什么我在执行期间收到 SIGTRAP?

python - 如何调整 Numpy 数组的大小以添加/替换行,其组合由数组每行中的值确定

php - 具有两个数组的多个 foreach

javascript - 在循环中生成具有属性的对象数组

python - 如何在 python 中定义多维数组?

C:打印数组中某个点的水平、垂直和倾斜值

matlab - 给定矩阵的 LUP 分解,如何在 MATLAB 中找到行列式?

c++ - Armadillo :将立方体 subview (管)转换为 vector

c++ - DLIB:具有 halen 数据集的 194 个地标的 train_shape_predictor_ex.exe 给出运行时错误:错误分配

C++ 类变量和默认构造