I have had the recent pleasure to explain pointers to a C programming beginner and stumbled upon the following difficulty. It might not seem like an issue at all if you alre
Perhaps stepping through it just a bit more makes it easier:
#include
int main()
{
int foo = 1;
int *bar = &foo;
printf("%i\n", foo);
printf("%p\n", &foo);
printf("%p\n", (void *)&foo);
printf("%p\n", &bar);
printf("%p\n", bar);
printf("%i\n", *bar);
return 0;
}
Have them tell you what they expect the output to be on each line, then have them run the program and see what turns up. Explain their questions (the naked version in there will certainly prompt a few -- but you can worry about style, strictness and portability later). Then, before their mind turns to mush from overthinking or they become an after-lunch-zombie, write a function that takes a value, and the same one that takes a pointer.
In my experience its getting over that "why does this print that way?" hump, and then immediately showing why this is useful in function parameters by hands-on toying (as a prelude to some basic K&R material like string parsing/array processing) that makes the lesson not just make sense but stick.
The next step is to get them to explain to you how i[0]
relates to &i
. If they can do that, they won't forget it and you can start talking about structs, even a little ahead of time, just so it sinks in.
The recommendations above about boxes and arrows is good also, but it can also wind up digressing into a full-blown discussion about how memory works -- which is a talk that must happen at some point, but can distract from the point immediately at hand: how to interpret pointer notation in C.