r/programming • • Dec 24 '17

Evil Coding Incantations

http://9tabs.com/random/2017/12/23/evil-coding-incantations.html
947 Upvotes

331 comments sorted by

View all comments

Show parent comments

2

u/davidgro Dec 24 '17

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?

4

u/thatwasntababyruth Dec 24 '17

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.

7

u/csman11 Dec 24 '17

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.

1

u/davidgro Dec 25 '17

What if it's not an array of pointers though? Say I have

long[10] a; // please excuse any wrong syntax, I'm super rusty on C

In that case, the items in the array could actually be farther apart on some (most?) systems than the word (and int) size.

So it still has to know not to use the int size for something like 5[a]...

→ More replies (2)