4

In thsi example:

int a[2][2]={{1,2},{3,4}};
int *p=a[0];
cout<<p;
cout<<&a[0][0];

Both gives the same output. Then why am I not able to call function (say fun)like this and loop through the array:

fun(a[0]);

fun(int *p)
{
cout<<p[1][1];
}
JoeG
  • 12,994
  • 1
  • 38
  • 63
Gautam Kumar
  • 1,162
  • 3
  • 14
  • 29
  • This is not a exact duplicate but You should have a look at this excellent faq entry: http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c – Alok Save Jul 11 '11 at 10:51

3 Answers3

3
fun(a[0]); //this looks OK

void fun(int *p) // this is OK if you add return type'
^^^^
{
   cout<<p[1][1]; //NOT OK!  You can't have 2 indices on an `int*`
   cout << p[1]; // OK, will print a[0][1]
}
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • Very nice. To be clear, this function `fun` accesses the 1-dimensional slices of the original 2-dim array. I don't really understand if that's what the OP wanted, so I thought best to spell that out. – Kerrek SB Jul 11 '11 at 10:56
2

To answer your question: when you write:

p = a[0];

a[0] (now 0th element to 1D array) actually decays to a pointer p. So both are not exactly the same type, though they appears to be. When you write:

fun(a[0]);

You are actually passing the 0the element of the array which is now a 1D array. So you can receive in either of below ways:

fun(int *p); // decay to pointer to 1D array
fun(int (&a)[2]); // receive array by reference

In both the case fun() has now a 1D array.

To make the things simpler, Pass reference to array:

void fun(int (&p)[2][2])
{
  cout<<p[1][1];  // ok !
}

Usage:

fun(a); // not a[0]
iammilind
  • 68,093
  • 33
  • 169
  • 336
0

You can't cout<<p[1][1];, because p is int * — a one-dimensional array.

vines
  • 5,160
  • 1
  • 27
  • 49