Passing 2D array as argument
In thsi example:
int a[2][2]={{1,2},{3,4}};
int *p=a[0];
cout<<p;
开发者_StackOverflowcout<<&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];
}
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]
}
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 0
the 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]
You can't cout<<p[1][1];
, because p
is int *
— a one-dimensional array.
精彩评论