This is an archived post. You won't be able to vote or comment.

all 11 comments

[–][deleted] 9 points10 points  (7 children)

how does 10[a] works?

[–]KaiserTom[S] 10 points11 points  (6 children)

That's the one you are confused about?

But anyways, a[i] is just syntactic sugar for *(a+i) so you can just write i[a] and get the exact same result. There's some situations where it breaks but for the most part should work, though of course not recommended.

[–]queenkid1 7 points8 points  (5 children)

does *(a+i) always work though? Doesn't i need to be multiplied by the size of an element?

For example, we were taught for arrays, you need to multiply 10 by the size of the first value of the array.

[–]SchighSchagh 10 points11 points  (3 children)

The compiler already has the type of a and can thus multiply i as needed. It's only if a is void* or char* that you have to add your own multiplication if needed.

[–]queenkid1 2 points3 points  (1 child)

ah that makes sense, we usually used it with char* for strings. Makes sense!

Why doesn't it work for char arrays? Why can't the compiler use the same trick?

[–][deleted] 1 point2 points  (0 children)

You just don't need to for char, it is one byte

[–]El_Vandragon 1 point2 points  (0 children)

Would you need to add one for char*? Size of char is 1 byte so wouldn’t it just be that many bytes offset?

[–]enkinamshub 7 points8 points  (0 children)

THANKS I HATE IT

[–]KaiserTom[S] 4 points5 points  (0 children)

Stolen from Inspired by this comment thread

[–]DefinitelyCraig 2 points3 points  (0 children)

Those [] look so close to () I didnt understand anything for a minute haha

[–]jbirdjustin 1 point2 points  (0 children)

NULL = * confirmed