4

why does the pointer array "equivalence" not work in the following case?

void foo(int** x) {
  cout << x[0][1];
}

int main( ) {
  int a[2][2] = {{1,2},{2,3}};
  foo(a);  
}

thank you

6
  • 6
    What doesn't work? what error message are you getting? Commented May 12, 2011 at 20:47
  • possible duplicate of In C, are arrays pointers or used as pointers? Commented May 12, 2011 at 20:48
  • The pointer array "equivalence" Commented May 12, 2011 at 20:49
  • @ildjam, no its not duplicate, there the 1D case is discussed for which the pointer array "equivalence" works Commented May 12, 2011 at 20:51
  • 4
    @user695652: ...Because there's no such thing as "pointer array equivalence" and there never was. In fact, your example is a direct proof of that. Commented May 12, 2011 at 20:53

3 Answers 3

11

The memory model of int** and int[2][2] is different.
int a[2][2] is stored in memory as:

&a     : a[0][0]
&a + 4 : a[0][1]
&a + 8 : a[1][0]
&a + 12: a[1][1]

int** x:

&x       : addr1
&x + 4   : addr2
addr1    : x[0][0]
addr1 + 4: x[0][1]
addr2    : x[1][0]
addr2 + 4: x[1][1]

while addr1 and addr2 are just addresses in memory.
You just can't convert one to the other.

Sign up to request clarification or add additional context in comments.

2 Comments

&x would be of type int*** ... did you mean *x or x[INDEX], where x is dereferenced to give the int* it's pointing to (which in this case is pointing to an array of type int)?
It's actually x instead of &x as it's the address of the 2 other addresses.
4

It doesn't work because only the first level of the multidimensional array decays to a pointer. Try this:

#include <iostream>
using std::cout;

void foo(int (*x)[2]) {
  cout << x[0][1];
}

int main( ) {
  int a[2][2] = {{1,2},{2,3}};
  foo(a);
}

Comments

0

because the type is not int **. this right for foo function

foo(int *[2]);

type of pointer a is not int ** , exactly int* [2]..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.