Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

  foo[3]
  *(foo + 3)
  *(3 + foo)
  3[foo]
They all do the same thing.


Interesting! I assume because the literal is being coerced to be the size of the variable? After all:

    foo[3] == (void *)((usize)foo + (usize)(3 * sizeof(*foo)))


Yeah, that's how pointer arithmetic works. Adding an int and a pointer assumes an array and gives you a pointer to the nth element in that direction (which had better exist, for your sake). char pointers can be used for byte offsets if a byte is a char on your platform (and it's been quite a while since that wasn't true).

You can also subtract two pointers into the same array and get the distance (in elements, not bytes). a[b - a] == b.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: