Skip to content

Comment on Ask HN: Favorite pointer tricks in C?

Comments

What I think takes the cake is this:

  array[index] == index[array]
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.

You didn't really spell out why this trick works:

    array[index] == *(array + index) == *(index + array) == index[array]

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

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])

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.

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.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.