Re:Ask HN: Favorite pointer tricks in C?
by jallmann on Saturday November 20, 2010 @05:10PM
(#1925478)
What I think takes the cake is this:
Not that you would actually use this, but it gave me a lot of insight into how addressing and stuff works inside the compiler. Also from this example, there's the implicit suggestion that an array can be treated as a pointer. So that leads into pointer arithmetic which can be very useful.
[ Parent
| on HN ]
You didn't really spell out why this trick works:
array[index] == *(array + index) == *(index + array) == index[array]
Re:Ask HN: Favorite pointer tricks in C?
by alan-crowe on Sunday November 21, 2010 @01:01PM
(#1927466)
array + index == index + array needs justification
One expects the generic + in a+i to get expanded to raw addition .+. and raw multiplication .x. with s the size of elements of the array
a .+. s .x. i
One expects index + array to throw a type error because index is just a number and doesn't have an element size.So I'm guessing that the real reason that the trick works is that generic + has three methods with signatures
int + int
array + int
int + array
Re:Ask HN: Favorite pointer tricks in C?
by dgallagher on Saturday November 20, 2010 @08:02PM
(#1925862)
The same as above, only using Pointer Arithmetic instead of Array Subscripting:
*(array + index) == *(index + array)
Further broken down: *(&array[0] + index) == *(index + &array[0])
Re:Ask HN: Favorite pointer tricks in C?
by jallmann on Saturday November 20, 2010 @08:36PM
(#1925926)
Yep. And if teaching that to a bunch of middle or high schoolers, I would add that pointer arith works in increments of sizeof(array[0]) bytes. If you're not careful about operator precedence in moderately complicated expressions, that could come back to bite you.
Re:Ask HN: Favorite pointer tricks in C?
by philwelch on Saturday November 20, 2010 @10:44PM
(#1926228)
This is a fantastic way to show younger or beginning programmers to think beyond what the code is supposed to denote and consider how it works in reality--in other words, the hacker's perspective. A naive programmer takes array[index] at face value. The hacker gets the idea that array[index] is just *(array + index) deeply enough to make a perverse joke out of it.