在c ++中将多维数组转换为指针 [英] Converting multidimensional arrays to pointers in c++
问题描述
我有一个如下所示的程序:
double [4] [4] startMatrix;
double [4] [4] inverseMatrix;
initialize(startMatrix)//这将我想要的信息放在startMatrix中
以计算startMatrix的逆,并将其放入inverseMatrix。我有一个库函数为此目的,其原型如下:
void MatrixInversion(double ** A,int order,double ** B)
取得A的倒数并将其放入B.问题是需要知道如何将double [4] [4]转换为double **来赋予函数。我试过只是做明显的方式:
MatrixInversion((double **)startMatrix,4, **)inverseMatrix))
但这似乎不工作。这是真正的方法吗?
不,没有正确的方法做到这一点。 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 * /};
并传递这些索引数组
MatrixInversion(startRows,4,inverseRows);
一旦函数完成工作,就可以忘记 startRows
和 inverseRows
数组,因为结果将被正确放入原始的 inverseMatrix
数组。 >
I have a program that looks like the following:
double[4][4] startMatrix;
double[4][4] inverseMatrix;
initialize(startMatrix) //this puts the information I want in startMatrix
I now want to calculate the inverse of startMatrix and put it into inverseMatrix. I have a library function for this purpose whose prototype is the following:
void MatrixInversion(double** A, int order, double** B)
that takes the inverse of A and puts it in B. The problem is that I need to know how to convert the double[4][4] into a double** to give to the function. I've tried just doing it the "obvious way":
MatrixInversion((double**)startMatrix, 4, (double**)inverseMatrix))
but that doesn't seem to work. Is that actually the right way to do it?
No, there's no right way to do specifically that. A double[4][4]
array is not convertible to a double **
pointer. These are two alternative, incompatible ways to implement a 2D array. Something needs to be changed: either the function's interface, or the structure of the array passed as an argument.
The simplest way to do the latter, i.e. to make your existing double[4][4]
array compatible with the function, is to create temporary "index" arrays of type double *[4]
pointing to the beginnings of each row in each matrix
double *startRows[4] = { startMatrix[0], startMatrix[1], startMatrix[2] , startMatrix[3] };
double *inverseRows[4] = { /* same thing here */ };
and pass these "index" arrays instead
MatrixInversion(startRows, 4, inverseRows);
Once the function finished working, you can forget about the startRows
and inverseRows
arrays, since the result will be placed into your original inverseMatrix
array correctly.
这篇关于在c ++中将多维数组转换为指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!