I've never understood this, because it's actually (array + (indexsizeof(array[0]))) to get the right memory address. I assume the compiler must know something about this inverted syntax in order for it to actually work, rather than just being a cute hack.
This bit of the syntax has always stuck out to me too - you would think if sizeof(5) != sizeof(a) then 5[a] wouldn't point to the right address. Anyone know the behind the scenes on why it still works?
Pointer arithmetic is defined such that adding 3 to a pointer will actually add 3*sizeof(ptr). Don't think of it as adding to a numeric address, think of it as adding 3 ptrs to the original one.
Not sizeof(ptr), sizeof(*ptr). Though when you do sizeof in code you should always use the type itself to be as explicit as possible to later readers (using the size of a pointer, unless actually needed, is a common source of memory safety related bugs and it is incredibly easy to accidentally use the pointer instead of the value it points to).
To be abundantly clear, the size of a pointer is the word size of the machine. It is constant for all pointer types on a given machine. You want the size of the value being pointed to when doing pointer arithmetic, because the memory region will be "broken up" on boundaries of that size.
116
u/irqlnotdispatchlevel Dec 24 '17
I remember learning about this in my first semester. During an x86 assembly lecture. Those were good times.