4 ms·
I dislike nitpicking, but the following is wrong: "In C, bodies[i] is exactly the same as *(bodies + i) — it performs pointer arithmetic and a dereference
by rvr_ 7y ago
I dislike nitpicking, but the following is wrong:
"In C, bodies[i] is exactly the same as *(bodies + i) — it performs pointer arithmetic and a dereference and nothing else. In particular, it assumes that you have some reason to know that i is a valid index for the array. This is the common case in C and gets a shorthand using square brackets."
In C, bodies[i] is not (bodies + i), with the exception being char arrays. The general rule is:
bodies[i] = *(bodies + i * sizeof(bodies[0]))
- heinrich5991 7y agoNo, it's actually defined to be the same. The pointer arithmetic in C follows your intuitive understanding of array indexing. #include <stdio.h> int main() { int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; printf("%d %d\n", array[4], *(array + 4)); return 0; } prints "4 4".
- barrkel 7y ago+ in C advances pointers in sizeof-pointed-to thing increments. It's why ++ works too. Similarly - on pointers returns a difference in units of sizeof-pointed-to thing.
- jcranmer 7y agoThe semantics of a[i] is exactly that of *(a + i). Which is why i[bodies] is actually legal C code.