简体   繁体   中英

Invalid output in `int` array

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 ie {9,12} and then [1] should dereference to first element ie 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}};

ie

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM