Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting multidimensional arrays to pointers in c++

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?

like image 883
Alex319 Avatar asked Oct 18 '09 05:10

Alex319


People also ask

How do you assign a two dimensional array to a pointer?

The simple answer is that you cannot. A bidimensional array is a contiguous block of memory that holds each line, while a pointer to pointer can refer to a memory location where a pointer to a different memory location containing the integers is.

How pointers can be used for declaring multi dimensional arrays?

When a pointer p is pointing to an object of type T, the expression *p is of type T. For example buffer is of type array of 5 two dimensional arrays. The type of the expression *buffer is “array of arrays (i.e. two dimensional array)”.

How is a multidimensional array defined in terms of an array of pointers?

An element in a multidimensional array like two-dimensional array can be represented by pointer expression as follows: **a+i+jIt represent the element a[i][j]. The base address of the array a is &a[0][0] and starting at this address the compiler allocates contiguous space for all the element row-wise.


1 Answers

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.

like image 116
AnT Avatar answered Sep 20 '22 18:09

AnT