Reputation: 1
And what would be stored in array **p
?
int main()
{
int i, a[2][2]={{1,2},{3,4}};
int (**p)[2];
p=a;
for(i=0;i<4;i++)
printf("%d ", *(*p+i));
return 0;
}
Upvotes: 0
Views: 229
Reputation: 46
The questioner's code does not compile:
int i, a[2][2]={{1,2},{3,4}};
int (**p)[2];
p=a;
error C2440: '=': cannot convert from 'int [2][2]' to 'int (**)[2]'
If the intention was to define a pointer to the 2x2 array a, then p should be defined as a pointer to array 2 of array 2 of int and used thus:
int main()
{
int a[2][2] = { {1,2},{3,4} };
int(*p)[2][2];
p = &a;
printf("{%d, %d} \n", (*p)[0][0], (*p)[0][1]);
printf("{%d, %d} \n", (*p)[1][0], (*p)[1][1]);
return 0;
}
The output is:
{1, 2}
{3, 4}
Upvotes: 0
Reputation: 153447
what does
int (**p)[2]
declare ?
p as pointer to pointer to array 2 of int
(Very useful site C gibberish ↔ English)
what would be stored in array
**p
?
In **p
an array 2 of int
.
p
is a pointer. p
would also store a pointer. That stored pointer in p
points to an array 2 of int
.
int array2[2] = {5, 7};
int (*pointer)[2] = &array2;
int (**p)[2] = &pointer;
printf("%d %d\n", (**p)[0], (**p)[1]); // output "5 7\n"
Upvotes: 3
Reputation: 310960
I think there is a typo in this declaration.
int (**p)[2];
There must be
int (*p)[2];
That is it is a declaration of a pointer to array of the type int[2]
And in this assignment
p = a;
the array a is implicitly converted to pointer to its first element that has the type int[2]
. That is in this assignment the right side hand operand has the type int ( * )[2]
and the left side hand operand has the same type.
Otherwise you will get a compilation array because the pointers int ( ** )[2]
and int ( * )[2]
are not compatible,
In this for loop
for(i=0;i<4;i++)
printf("%d ", *(*p+i));
there is in fact reinterpretation of the pointer to the type int *
. As the pointer p
has the type int ( * )[2]
then dereferencing it you get lvalue of the type int[2]
but used in the expression *p+i
this array in turn is converted to pointer to its first element. That is inside the expression *p+i
you have pointer to the element a[0][0]
.
You could rewrite the expression
*(*p+i)
like
( *p )[i]
If to use a pointer of the type int( ** )[2] then the body of the function main could look like
int i, a[2][2]={{1,2},{3,4}};
int (*q)[2] = a;
int ( **p )[2] = &q;
for(i=0;i<4;i++)
printf("%d ", *( **p +i ) );
That is one more indirection of accessing elements of the array is added.
Upvotes: 0