0

Possible Duplicate:
How do I use arrays in C++?

How do I pass 2-D array to function in c++ via pointer. I get following error when I try the code below.

error: cannot convert 'int (*)[10][10]' to 'int **' for argument '1' to 'void fn(int **)'

void fn(int **a)
{
cout<<a[0][0]<<" "<<a[0][1];
}

int main()
{

int A[10][10];
A[0][0]=1;
A[0][1]=2;

fn(&A);   //????
}
Community
  • 1
  • 1

5 Answers5

2

A 2d array, created the way you did, is contigous in memory. The compiler needs to know the size of each segment, to be able to move the pointer to the next one in your function. Writing fn(int (*a)[3]) or fn(int a[][3]) is equivalent. But let's take an example

char a[3][3];

a[0][0] = 01;
a[0][1] = 02;
a[0][2] = 03;
a[1][0] = 04;
a[1][1] = 05;
a[1][2] = 06;
a[2][0] = 07;
a[2][1] = 08;
a[2][2] = 09;

will become

|01|02|03|04|05|06|07|08|09|

in memory.

So if you pass a to a function, it needs to know that it has to increase the a ptr by 3 * sizeof(a) to access a[1][0].

In short : the prototype of the function needs to be void fn(int a[][10]) or void fn(int (*a)[10])

tomahh
  • 13,441
  • 3
  • 49
  • 70
1

According to the link from @R. Martinho Fernandes , the following is valid C++:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

So the following should also be valid:

void fn (int (*a)[10]) 
{
     cout<<a[0][0]<<" "<<a[0][1];
}

And I believe the following is also valid:

void fn (int a[][10]) 
{
    cout<<a[0][0]<<" "<<a[0][1];
}
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
Geoff Montee
  • 2,587
  • 13
  • 14
0

You need to declare fn() as

void fn(int (&a)[10][10])
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
perh
  • 1,668
  • 11
  • 14
0

C++ needs to know the array size (of one dimension) to perform 2d indexing.

try:

void fn(int a[][10]) {
    cout<<a[0][0]<<" "<<a[0][1]; 
}
Rudolf Mühlbauer
  • 2,511
  • 16
  • 18
0

Arrays in C++ can be treated as pointers to the location of the first element of an array. A two dimensional array can be thought of as an array of pointers, and each of the pointers points to another array. While this isn't strictly speaking how arrays are implemented, C supports implicit conversion between arrays and pointers to the first element, and you can think of them as the same. Array[index] is just syntactical sugar for *(Array + index*sizeof(whatever's in the array)). So for your function to work, you can just do:

void fn(int (*a)[10]) {
    cout<<a[0][0]<<" "<<a[0][1];
}

int main() {

    int A[10][10];
    A[0][0]=1;
    A[0][1]=2;

    fn(A);
}

No need to get the address of the array first, because it's already a pointer. However, because you're using C++, you really should consider using standard containers:

void fn(vector< vector<int> > const&a) {
    cout<<a[0][0]<<" "<<a[0][1];
}

int main() {

    vector< vector<int> > A( 10, vector<int>(10) );
    A[0][0]=1;
    A[0][1]=2;

    fn(A);
}
Rose Kunkel
  • 3,102
  • 2
  • 27
  • 53