-1

I have a question about how to pass a 2D array to a function.

I know I can do things like this:

void print(int a[][20]){
    cout << "print 1" << a[10][10] << endl;
}
int main(){
    int a[20][20];
    print(a);
    cout << "print 2" << *(*(a+10)+10) << endl;
}

print 1 and 2 should give me the same result.
a is a 2D pointer if I am correct.

But I cannot do this

void print(int** a){
}
int main(){
    int a[20][20];
    print(a);
    cout << "print 2" << *(*(a+10)+10) << endl;
}

The error is:
cannot convert ‘int (*)[20]’ to ‘int**’ for argument ‘1’ to ‘void print_int(int**)’
Why I cannot do this?

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
sflee
  • 1,659
  • 5
  • 32
  • 63

3 Answers3

2

int ** is a pointer to a pointer to a int, not a 2d array.

Daniele Vrut
  • 2,835
  • 2
  • 22
  • 32
1

Because int ** is a "pointer to pointer to int". It is not same as "pointer to twenty ints". So your second code is same as trying to pass address of street where your house stays instead of passing address of somebody who has address from your home.

0

You should be using array notation, not pointer notation as arrays aren't pointers:

cout << "print 2" << a[11][11] << endl;
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • @Angew You're right, and normally I know it, I wanted to say something else but got confused by 2-dimensional arrays in C :-) – Seg Fault Oct 18 '13 at 13:10