c++ - How to call a function with a parameter typed high-dimensional array by passing a pointer? -


for example, have function (need c99)

void fun(int nx, int ny, double a[nx][ny]) {     // code here } 

and have pointer

double *p = new double[nx * ny]; 

and use call function like

fun(nx, ny, p); // error type not matched 

how it? type conversion allowed.

what want not possible in c++ because c++ requires sizes of array types compile time constants. c99 not have limitation, function declaration

void fun(int nx, int ny, double a[nx][ny]); 

is valid c99, not valid c++. btw, in c99, correct call of function this:

int nx = ..., ny = ...; double (*matrix)[ny] = malloc(nx*sizeof(*matrix)); fun(nx, ny, matrix); 

now, have 2 possibilities:

  1. use c multidimensional array stuff.

  2. use c++ workaround this.


the easiest c++ workaround vector<vector<double> >. avoid hassle of allocating memory yourself, however, rows in 2d matrix not consecutive.


you can use 2 layer indirection this:

double **matrix = new double*[nx]; for(int = 0; < ny; i++) matrix[i] = new double[ny]; 

and declare function as

void fun(int nx, int ny, double** a); 

note need 1 additional index array in addition arrays hold data. however, free use single large array hold data:

double** matrix = new double*[nx]; double* storage = new double[nx*ny]; for(int = 0; < ny; i++) matrix[i] = &storage[ny*i]; 

the final possible workaround is, index calculation yourself:

void fun(int nx, int ny, double* twodarray) {     //access array     twodarray[x*ny + y]; }  //somewhere else double* matrix = new double[nx*ny]; fun(nx, ny, matrix); 

this c99 under hood code @ top, less type checking.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -