Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `*(*(p+1)+1)[7]` equal `p[1][8][0]`?

Tags:

c

pointers

char *p[2][3];

How does *(*(p+1)+1)[7] equal p[1][8][0]?

I thought *(*(p+1)+1)[7] would be the same as *(*(*(p+1)+1)+7) and that is equal to p[1][1][7], where am I wrong?

E: I don't understand why this is being downvoted...

like image 218
YoTengoUnLCD Avatar asked Feb 21 '26 09:02

YoTengoUnLCD


2 Answers

Basic facts:

  1. [] associates left to right
  2. [] has higher precedence than the dereference operator *
  3. a[i] is *(a+i)

So

  *(*(p+1)+1)[7] 
= *((*(p+1)+1)[7])   // rule 2
= *(*(*(p+1)+1+7))   // rule 3
= *(*(*(p+1)+8))    
= *(*(*(p+1)+8)+0)  
= p[1][8][0]         // rules 1 and 3
like image 63
WhiteViking Avatar answered Feb 24 '26 00:02

WhiteViking


This depends on the relative precedence of [] vs unary * (the former is higher), and the essential identity that if p is (or evaluates to) a pointer and n is of integer type then p[n] means the same thing as *(p + n). You can therefore transform your starting expression according to the following steps, making repeated use, in both directions, of that identity:

  1. *(*(p+1)+1)[7]
  2. == *((*(p+1)+1)[7]) (The added parentheses express the operator precedence explicitly.)
  3. == *((p[1]+1)[7])
  4. == *(*((p[1]+1)+7))
  5. == *(*(p[1]+1+7))
  6. == *(*(p[1]+8))
  7. == *(p[1][8])
  8. == *(p[1][8] + 0)
  9. == p[1][8][0]
like image 31
John Bollinger Avatar answered Feb 23 '26 22:02

John Bollinger