Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 2-D array as argument

Tags:

c++

pointers

I am trying to pass a 2-d array to a function which accept a pointer to pointer. And I have learnt that a 2-d array is nothing a pointer to pointer(pointer to 1-D array). I when I compile the below code I got this error.

#include<iostream>

void myFuntion(int **array)
{
}
int main()
{
   int array[][]= {{1,2,3,4},{5,6,7,8,9},{10,11,12,13}};
   myFuntion(array);
   return 0;
}

In function 'int main()': Line 5: error: declaration of 'array' as multidimensional array must have bounds for all dimensions except the first compilation terminated due to -Wfatal-errors.

Can anybody clear my doubt regarding this and some docs if possible for my more doubts.

like image 523
yogi Avatar asked Oct 20 '12 16:10

yogi


2 Answers

  void myFunction(int arr[][4])

you can put any number in the first [] but the compiler will ignore it. When passing a vector as parameter you must specify all dimensions but the first one.

like image 109
vmp Avatar answered Sep 27 '22 17:09

vmp


Another templated solution would be:

template<int M, int N>
void myFunction(int array[N][M])
{
}
like image 35
Matthieu Brucher Avatar answered Sep 27 '22 17:09

Matthieu Brucher