hodondo
hodondo

Reputation: 91

pointer arithmetic confusion with number and address

I am confused as to how to work out the solution for this:

4 - (( h + 4 ) - &h[6]) + &h[2] + 5 + (&h[3] - (h+6))

my approach is:

4 - (( &h[4] - &h[6]) + &h[2] + 5 + (&h[3] - &h[6])) // &h[4] - &h[6] + &h[2] = 0 (is this correct?)
4 - ( 0 + 5 + (&h[3] - &h[6])) // &h[3] - &h[6] = -3 
4 - ( 5 -3)) //
4 - ( 2))
2


but this is not correct

Upvotes: 1

Views: 60

Answers (1)

pmg
pmg

Reputation: 108986

I see it like this:

   4 - (( h + 4 ) - &h[6]) + &h[2] + 5 + (&h[3] - (h + 6))
//int    ptr int     ptr      ptr   int    ptr    ptr int

// convert &a[i] to (a + i)
   4 - (( h + 4 ) - (h + 6)) + (h + 2) + 5 + ((h + 3) - (h + 6))
//int    ptr int    ptr int    ptr int  int   ptr int   ptr int

   4 - (-2) + (h + 2) + 5 + (-3)
//int  int    ptr int  int   int

   6 + (h + 2) + 2
//int  ptr int  int

   h + 10
//ptr int --- same as &h[10]

Upvotes: 4

Related Questions