-4

Somehow these pointer arithmetics are very confusing to me. An example:

uint16_t *a = (uint16_t *)0x200;
a += 4 * sizeof(uint32_t);

When calculating the new value of a, what is your thought process?

This is how I am trying to figure it out:

  1. The pointer (a) points to an address, which has a value of 0x200 of uint16_t type.
  2. The second operation moves the pointer a to a + 4 * 8 bytes to a location 32 bytes (20 in hex) further up, which is apparently 0x220. How come this is not &a + 32? I think this is where I confuse things... Why is the pointer pointing to 0x200 and not &a?
Space
  • 51
  • 1
  • 10

1 Answers1

2

Pointer arithmetic is in units of the type being pointed to.

So if you just did ++a;, the new value of a would be 0x202, not 0x201.

So, when you add 4 * sizeof (uint32_t), that is the same as adding 2 * 4 * 4, i.e. 32, which is hex 0x20. So the new value is 0x220.

unwind
  • 391,730
  • 64
  • 469
  • 606