Hacker News new | ask | show | jobs
by JTyQZSnP3cQGa8B 1175 days ago
I haven't used pointer arithmetic for a long time but the "value" of the index depends on the type, doesn't it? For a char[], it's (a + index), but for an int[] it should be (a + 4*index), or (a + sizeof(type)*index).

I have never understood how the compiler is supposed to know that it's (a + 4*index) and not (index + 4*a) which gives different results. Maybe it's based on the type itself and the computation is done by multiplying the "integral" index with it's size, and adding the "pointer" if there is one.

But even this can give wrong values if you're on an embedded platform where you can store your pointers as integers, size_t, or simple defines without a type.

If anyone knows where I can find the explanation in the standard, I've been wondering about it for at least 20 years...

Edit: it seems that a simple example gives the solution: (void*)[void*] is invalid, and int[int] is invalid too, therefore the compiler will get the pointer as the address, and the integral type as the index. I feel stupid for not testing this earlier.

1 comments

When you do `*(pointer + 1)`, it'll actually increment the address of the pointer by `sizeof(*pointer)`, so it indeed works the same as indexing `pointer[1]`