将多维数组转换为c ++中的指针

Ale*_*319 14 c++ pointers multidimensional-array

我有一个如下所示的程序:

double[4][4] startMatrix;
double[4][4] inverseMatrix;
initialize(startMatrix) //this puts the information I want in startMatrix
Run Code Online (Sandbox Code Playgroud)

我现在想要计算startMatrix的反转并将其放入inverseMatrix.我有一个用于此目的的库函数,其原型如下:

void MatrixInversion(double** A, int order, double** B)
Run Code Online (Sandbox Code Playgroud)

取A的倒数并将其放入B.问题是我需要知道如何将double [4] [4]转换为双**以赋予函数.我尝试过"明显的方式":

MatrixInversion((double**)startMatrix, 4, (double**)inverseMatrix))
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.这实际上是正确的方法吗?

AnT*_*AnT 24

不,没有正确的方法可以做到这一点.甲double[4][4]阵列是无法转换为一个double **指针.这是实现2D阵列的两种不同的,不兼容的方式.需要更改某些内容:函数的接口或作为参数传递的数组结构.

执行后者的最简单方法,即使现有double[4][4]数组与函数兼容,是创建double *[4]指向每个矩阵中每行开头的临时"索引"数组

double *startRows[4] = { startMatrix[0], startMatrix[1], startMatrix[2] , startMatrix[3] };
double *inverseRows[4] = { /* same thing here */ };
Run Code Online (Sandbox Code Playgroud)

并传递这些"索引"数组

MatrixInversion(startRows, 4, inverseRows);
Run Code Online (Sandbox Code Playgroud)

函数完成后,您可以忘记startRowsinverseRows数组,因为结果将正确放入原始inverseMatrix数组中.


Unc*_*ens 5

由于给定的原因,二维数组(一个连续的内存块)和一个指针数组(不连续)是非常不同的东西,你不能将二维数组传递给使用指针到指针的函数.

你可以做的一件事:模板.使第二个维度的大小成为模板参数.

#include <iostream>

template <unsigned N>
void print(double a[][N], unsigned order)
{
    for (unsigned y = 0; y < order; ++y) {
        for (unsigned x = 0; x < N; ++x) {
            std::cout << a[y][x] << ' ';
        }
        std::cout << '\n';
    }
}

int main()
{
    double arr[3][3] = {{1, 2.3, 4}, {2.5, 5, -1.0}, {0, 1.1, 0}};
    print(arr, 3);
}
Run Code Online (Sandbox Code Playgroud)

另一种,有点笨拙的方法可能是让函数接受指向一维数组的指针,并将宽度和高度作为参数给出,并自己将索引计算为二维表示.

#include <iostream>

void print(double *a, unsigned height, unsigned width)
{
    for (unsigned y = 0; y < height; ++y) {
        for (unsigned x = 0; x < width; ++x) {
            std::cout << a[y * width + x] << ' ';
        }
        std::cout << '\n';
    }
}

int main()
{
    double arr[3][3] = {{1, 2.3, 4}, {2.5, 5, -1.0}, {0, 1.1, 0}};
    print(&arr[0][0], 3, 3);
}
Run Code Online (Sandbox Code Playgroud)

当然,矩阵是值得拥有它自己的类(但如果你需要编写辅助函数,上面可能仍然是相关的).