4 ms·
I knew about the first sentence, but the second really obscure. Accessing an element of an array via ptr[3] is actually just short for *(ptr + 3). Thi
by kalimatas 13y ago
I knew about the first sentence, but the second really obscure.
Accessing an element of an array via ptr[3] is actually just short for *(ptr + 3).
This can be equivalently written as *(3 + ptr) and therefore as 3[ptr], which turns out to be completely valid code.
- Skinney 13y agoThis was actually written in the book I used to learn C (I think, at least I knew this early on). It seems completely irrational when someone tells you that ptr[3] == 3[ptr], but with the above explination it makes perfect sence.
- chmike 13y agoYes and it also explains why array indexing starts at 0.
- unfamiliar 13y agoNot really. It would be just as easy to say a[x]=*(a+x-1) and let array indices start at 1.
- valisystem 13y agoactually yes, [] derives from BCPL, see evincarofautumn comment just above. ( link to comment, https://news.ycombinator.com/item?id=6886488 https://news.ycombinator.com/item?id=6886488 derived from this submission : https://news.ycombinator.com/item?id=6879478 https://news.ycombinator.com/item?id=6879478 )
- evincarofautumn 13y agoThe BCPL infix “!” operator makes it a bit clearer, I think: BCPL C !a *a a ! 0 a[0] 0 ! a 0[a] !(a + 0) *(a + 0) !(0 + a) *(0 + a) That’s where C got its 0-based semantics from—it would be a nasty surprise if 0 weren’t the identity for pointer addition!
- ygra 13y agoThe second one actually just follows from the first one. Because indexing is just a + operator, you can reorder the operands without changing the result.
- eXpl0it3r 13y ago> What square brackets really mean The title to that paragraph is miss leading, it's true for array but for a class brackets can do whatever the developer implements them to do.