Hacker News new | past | comments | ask | show | jobs | submit login

I've been programming C++ for too long to really understand why people find pointers hard, but I do remember that I did too at the beginning, and I do remember my epiphany (reading on the train, funny how I remember such senseless details 15 years later yet can't memorize a 4-item shopping list): given a declaration of

    struct Foo {
        int a;
    };
    Foo* f;
, the following two are equivalent:

    int b = f->a;
and

    int b = (*f).a;
Never had it spelled out for me like this, probably because it's so obvious once you get it - thought I'd share in case it gives anyone else an 'aha' moment.



The trick to teaching pointers is to model memory with boxes. You have a stack, and a heap, and you draw arrows to represent pointers. At some point, you need to reveal that those arrows are just numeric indices, but the visual helps early on. The * and & operators just let you follow the value in the pointer. I've had a number of students who were baffled up until I showed them this model.

Notational Machine for the win!


Back in the 80s the programming books I used always showed memory as little lines of boxes.

https://usborne.com/browse-books/features/computer-and-codin...


In general, thinking of memory as an array of bytes is helpful, and each byte has an address which is itself a series of bits that can be stored in memory --- and the concept that ties it all together and what I find makes a lot of people just "get it" is the fact that memory can itself store addresses that denote locations within it.


That's a perfect example of how knowing some assembly code helps with learning C.


i also had trouble with pointers while learning C, and, like everyone else, it seems so obvious now that i wonder what the hell my problem was. like learning to ride a bike, or drive a car with a manual transmission. i learned 8086 assembler before C and had no difficulty with indirection there.

for what its worth, your "aha" scenario would have just confused me more. even today, i have to think a bit before your second example makes sense to me.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: