I am trying to learn pointers and I just encountered a situation I do not understand.
int main()
{
int num[3][2]={3,6,9,12,15,18};
printf("%d %d",*(num+1)[1],**(num+2));
}
As per what I have learnt the output should be :
12 15
but actually it is:
15 15
Why? Please clarify as to how things are calculated here as what I think is first *(num+1)
get calculated and point to the 1st one i.e. {9,12}
and then [1]
should dereference to first element i.e 12
.
I am using GCC compiler.
In your data,
int num[3][2]={3,6,9,12,15,18};
equivalent to:
int num[3][2]={{3,6},{9,12},{15,18}};
i.e.
num[0][0] = 3
num[0][1] = 6
num[1][0] = 9
num[1][1] = 12
num[2][0] = 15
num[2][1] = 18
thus,
*(num+1)[1]
= *(*(num+1+1))
= num[2][0]
=15
and,
**(num+2))
= num[2][0]
=15
Array subscript []
operator has higher precedence than dereference operator *
.
This means the expression *(num+1)[1]
is equivalent to *((num+1)[1])
And if we take it apart
*(*((num+1)+1))
*(*(num+2))
*(num[2])
num[2][0]
See C Operator Precedence, []
is processed before *
That means
(num+1)[1]
*((num+1)+1)
*(num+2)
Together with the additional *
(not written in my example),
it becomes the same as the second thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With