Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid output in `int` array

Tags:

c

pointers

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.

like image 417
Suraj Avatar asked Oct 16 '14 07:10

Suraj


3 Answers

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
like image 66
Dr. Debasish Jana Avatar answered Oct 31 '22 18:10

Dr. Debasish Jana


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]
like image 28
2501 Avatar answered Oct 31 '22 16:10

2501


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.

like image 18
deviantfan Avatar answered Oct 31 '22 17:10

deviantfan