3 ms·
Agreed, and I never made the connection that array[index] could be written as index[array] haha.
by arcticbull 7y ago
Agreed, and I never made the connection that array[index] could be written as index[array] haha.
- anticensor 7y agoOnly if index and array have the types of same size. Because pointer arithmetic works in terms of object sizes, not in individual bytes.
- erik_seaberg 7y agofoo[3] *(foo + 3) *(3 + foo) 3[foo] They all do the same thing.
- arcticbull 7y agoInteresting! 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)))
- erik_seaberg 7y agoYeah, 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.
- harry8 7y agotypedef struct thing { char a; long long int nothing; } thing_t; #define P(x) printf("%s %c\n", #x, x) int main(int argc, char **argv) { thing_t array[1024]; array[8].a = 'H'; P(array[8].a); P((8[array]).a); P((*(8 + array)).a); }