How can I pass a multidimensional array to a function in C/C++ ?
The dimensions of array are not known at compile time
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
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)
Use a vector of vectors, you can pass a vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With