Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a dynamic multidimensional array to a function?

Tags:

c++

c

How can I pass a multidimensional array to a function in C/C++ ?

The dimensions of array are not known at compile time

like image 314
user380731 Avatar asked Jul 01 '10 04:07

user380731


3 Answers

A pointer to the start of the array along with the dimensions - then do the array arithmetic in the function is the most common solution.

Or use boost

like image 186
Martin Beckett Avatar answered Oct 30 '22 23:10

Martin Beckett


Passing the array is easy, the hard part is accessing the array inside your function. As noted by some of the other answers, you can declare the parameter to the function as a pointer and also pass the number of elements for each dim of the array.

#define xsize 20
#define ysize 30
int array[xsize][ysize];
void fun(int* arr, int x, int y)
{
 // to access element 5,20
 int x = arr[y*5+20];
}

fun(array, xsize, ysize);

Of course, I've left out the whole business of allocating the array (since it isn't known what its size will be, you can't really use #defines (and some say they're bad anyhow)

like image 23
Tom Avatar answered Oct 30 '22 22:10

Tom


Use a vector of vectors, you can pass a vector.

like image 33
thomasfedb Avatar answered Oct 30 '22 23:10

thomasfedb