75

In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.


Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers syntactically in C. I heard two of my friends explaining pointers to another friend, who asked why a struct was passed with a pointer. The first friend talked about how it needed to be referenced and modified, but it was just a short comment from the other friend where it hit me: "It's also more efficient." Passing 4 bytes instead of 16 bytes was the final conceptual shift I needed.

12
  • 16
    'Shotgun' method: throw *s everywhere til it works.
    – Michael K
    Nov 9, 2010 at 15:15
  • 15
    @Michael: Yeah, good luck with that. Nov 9, 2010 at 15:44
  • 8
    This question comes up shortly after at the start of every semester on SO. The latest incarnation is here: stackoverflow.com/questions/4118647/…
    – Tim Post
    Nov 9, 2010 at 16:22
  • 12
    What's a nice explanation for pointers? Brian Kernhigan and Dennis Ritchie hate software engineers. Nov 9, 2010 at 16:51
  • 3
    It "clicked" for me after having spent some time single-stepping machine code in the debugger. Yes, I was familiar with basics of computer architecture -- I learned assembly on Commodore 64, and x86 ASM was pretty straightforward after that. So I already knew the concept of an "address", I just didn't understand how it mapped to C's syntactical constructs.
    – zvrba
    Nov 10, 2010 at 11:27

32 Answers 32

26
+100

Memory-as-a-Grid Diagram

Usually what I do is represent memory as a "grid", so that I can make up addresses, highlight different memory spaces and write in the cells values (or even further, their binary representations) and link the pointers in memory to the values they point at. (And then still mention that it's a simplification).

Usually it's a "ohhhh" moment for most of my students.

Symbol Juggling

Then when it comes to have them stop forgetting how to use & and *, it's very simple: present it the same way they do math or physics calculations. If you divide a distance in km by a time in hour, you get a speed in km/h. What's in needs to be out. Simple.

printf to the Rescue

Doing just a few basic examples that visually represent what you explained with these will comfort them in what they think they understood, or give them the opportunity to say "ah, I don't get this one".

Be Extensive

Cover pointers for simple types and make sure they understand the difference between addressing and the size of a data type, then structs, then arrays, and multiple levels.

Then start pointer arithmetic.


Addendum: Recursion

I usually explain recursion similarly, using a visual representation. Have them print the alphabet using a pre-made function that writes a single char, and then ask them to print it in reverse order by just changing two lines.

Usually there's a "what the...?" moment, and when you add just another parameter to your printf to print numeric values and indent the steps, it becomes a sigh of relief.


Alternatives: The Play-Doh Model and the Water Cups

I actually had some co-workers in a university who showed students a video explaining pointers and memory accesses using play-doh paste. It was incredibly clever and well done, though I never really used that technique myself, except for very young learners interested in grasping programming (but usually those I wouldn't lead them towards a language using pointers too early). Basically using tiny balls of play-doh which you can attach to other bigger balls of play-doh representing memory spaces, and that you can combine together to either link them (like in a linked data structure) or merge together (as in a contiguous memory space). Using different colors for the memory spaces pointed to and the pointers help as well. But I still think the Memory-as-a-Grid thing works better, as you can clearly show that the pointing is really a matter of "addressing", as on a "map/grid". Whereas the Play-doh mode still confuses them into thinking that things really "touch" each other in memory.

The Water Cup thing was used directly by a colleague as well, but I don't know if she came up with it. It was an interesting approach, but I noticed many students were left puzzled by the explanation. Something alike to DevSolo's Coffee Cup technique. But I think it's actually a misleading one as you make the students confuse containers, data structures, pointers and arrays. It might be an interesting approach to explain arrays at the beginning I assume, but I wouldn't stick to it very long.

2
  • Wow, thanks for the bounty. Glad the answer was appreciated.
    – haylem
    Nov 17, 2010 at 22:34
  • Draw it out :| that sounds like some good teaching!
    – Spooks
    Mar 11, 2011 at 21:43
81

Someone much wiser than I once said:

The nun Wu Jincang asked the Sixth Patriach Huineng, "I have studied the Mahaparinirvana sutra for many years, yet there are many areas i do not quite understand. Please enlighten me."

The patriach responded, "I am illiterate. Please read out the characters to me and perhaps I will be able to explain the meaning."

Said the nun, "You cannot even recognize the characters. How are you able then to understand the meaning?"

"Truth has nothing to do with words. Truth can be likened to the bright moon in the sky. Words, in this case, can be likened to a finger. The finger can point to the moon’s location. However, the finger is not the moon. To look at the moon, it is necessary to gaze beyond the finger, right?"

10
  • 13
    +1 for dereferencing the moon. +1 for the koan, if I could.
    – Tim Post
    Nov 9, 2010 at 16:30
  • 15
    What is the sound of one finger upvoting? Nov 9, 2010 at 16:49
  • 3
    @Adam that depends on whether you're using a mouse or a trackpad. Nov 9, 2010 at 16:54
  • 7
    @Frank It was a GREAT quote. Still I think it will not help to grasp the idea. Specially to someone new to pointers.
    – Gulshan
    Nov 11, 2010 at 8:36
  • 11
    This is a beautiful story...but I suspect that people are up-voting because of that, rather than because it explains pointers well.
    – Kyralessa
    Nov 11, 2010 at 23:06
47

I found that diagrams were very helpful. Example:

pointer diagram


This sort of diagram helped me see that pointers were their own variable, but contained a value that was the location of another object, i.e. array or string. Also, when done in pencil, I could use it to trace my program on paper, or on a chalkboard/whiteboard.

3
  • 4
    Either the value within "pointer" should be 4 or the array indices (or memory addresses) should start from 0. Otherwise, how can a pointer that holds the value 3 point to location 4?
    – MAK
    Nov 9, 2010 at 19:43
  • ++ This is exactly how I was going to explain it. I started out in Fortran (for better or worse!). In Fortran, way back then, we used parallel arrays instead of arrays of structs (no such thing as new). If one array contained an index of "another row" in the arrays, we called it a "pointer", and this was exciting. We made linked lists, trees, you name it. Nov 9, 2010 at 20:59
  • 2
    I find pointers best explained using pictures indicating what's stored where, and arrows to indicate where pointers point.
    – gablin
    Nov 10, 2010 at 21:14
32

When I first "learned" about pointers, I was sort of thrust in to it. My university had made the decision a long time before I enrolled to center the curriculum around Java, so when my Data Structures professor gave one lecture on C and asked us to implement an XOR-List with pointers I felt like I was getting in to something way over my head.

I understood the definition:

A pointer is a variable that contains an address of a variable

But I still didn't understand a large part of the concept. Looking back, I think it centered on three things:

  1. What exactly is a memory location? (At the time I didn't take a Computer Organization class)

  2. The awkward syntax (So um... why exactly is it defined like "int *ip" but then subsequently I refer to the variable as "ip"?)

  3. How exactly is it beneficial to store the address of a variable rather than just use the variable?

It wasn't until I purchased the K&R book and completed every problem that I really got a grasp for pointers. Besides the fact that I had long completed the Computer Organization class (that I think should be required before learning C), part of it had to do with the fact that I realized that pointers can be used for functions, arrays, structs... to do useful things and not merely as storage for addresses of ordinary variables.

But my "aha" moment by far was the way that K&R explained the awkward syntax of defining a simple pointer. I took notes throughout the book (in which I rephrase points made by the book in to my own words in order to further my understanding), and this is the one relating to that:

A pointer is a variable that contains an address to a variable. A pointer is both defined and dereferenced (yielding the value stored at the memory location that it points to) with the '*' operator; the expression is mnemonic.

Ex.: 
   int a;      /* Variable 'a' is an integer */

   int *ip;   /* Variable ip is a pointer and dereferencing it gives an integer.
                 In other words, the expression *ip is an int, so ip is a pointer
                 to an int */

I had always felt that I couldn't fully grasp the more advanced concepts of pointers until I had something so elementary ingrained in my head. It had bothered me endlessly after that assignment (which I didn't do too well on, by the way ;) ) why "*ip" did not exist right after I (thought I) defined "*ip". Mastering this is essential for more advanced concepts involving pointers, like function pointers and more complicated definitions like this:

char (*(x())[])()

All in all, I think the concept of pointers requires:

  1. A basic understanding of how memory is laid out in a computer (and what memory is).

  2. Knowledge of how powerful pointers can be (real world usage, not just another abstract concept that they learn for the sake of learning).

  3. Deciphering the hieroglyphics colloquially known as "a definition of a pointer"

So all in all, I think there should be at least 3 "aha" moments when learning about pointers. I'm still a student so I thought you'd appreciate the viewpoint of someone who's still (relatively) fresh off learning the concept.

3
  • +1 for the 3 "Ah ha!" monents. Groking pointers comes in layers. I "understood" points for a long time before I realised I only about half understood pointers to pointers :) Nov 9, 2010 at 16:47
  • I think that you are totally correct in that a very large part of 'not understanding pointers' is actually tripping on the weird C syntax. [Thinks: I wonder how difficult it would be to grok with this kind of syntax: PointerTo<int> a]
    – Benjol
    Nov 10, 2010 at 5:41
  • Agreed, @Benjol. I'm surprised that the syntax int* ip isn't more common. I finally started understanding pointers once I saw code that was formatted like this. Then I could read it as "ip is of type int pointer."
    – Jacob
    Nov 11, 2010 at 22:47
20

Pointer are a bit like the application shortcuts on your desktop. Delete the shortcut and the target still exists. Start up the shortcut and the target gets started.

I always explain the working of this by simple creating a txt file on my desktop and two shortcuts to the file. After copying and deleting the shortcuts you can see people understand the idea behind 'references'.

Once the group understands the basic behind the shortcuts you can start explaining pointers anyway you want. They'll probably understand it pretty easily.

3
  • That is not a bad analogy. Just a few points to add for anyone taking this literally a "hard-link" will always point to its target even if it changes directories, a pointer will point to the original memory even if the object has been relocated. A "hard-link" will tell you when the target no longer exists, a dangling pointer pointer should be set to NULL.
    – snmcdonald
    Nov 10, 2010 at 11:48
  • A hard link is like a reference counted smart pointer
    – jk.
    Jan 12, 2011 at 13:14
  • 1
    +1. One of the best practical analogies to explain pointers. I am sure students would get the idea immediately as this functionality is the most commonly used by everyone. Mar 7, 2012 at 6:28
15

8-10 years ago, I taught an intro "C" course at a community college. This was always a fun topic to explore. What seemed to work best, and this was after discussing w/ a co-worker a few times was to use a coffee cup and your hand.

I used the analogy of a coffee cup (or row of them for arrays) to as a variable (it can hold something). I then used my hand, which could also hold something or, by extending my index finger to "point to" a coffee cup.

A close hand was null, a finger pointing at my head (like a mock gun) was a dangling pointer.

Then with a few demonstrations and trips through the debugger, it clicked with most.

6
  • 4
    You've already confused me. Nov 9, 2010 at 19:21
  • 1
    @Kirk, how so? let me see if I can clear it up.
    – DevSolo
    Nov 9, 2010 at 19:42
  • 4
    ++ There's nothing like teaching to make you think about these things. Nov 9, 2010 at 21:03
  • One of my lecturers at university did a similar thing, using students (one of whom was "Niel", for added laughs), instead of the coffee cup. Pointing hand-wavedly at the audience was a dangling pointer, because it could be pointing to anything.
    – Kaz Dragon
    Dec 10, 2010 at 14:28
  • 2
    A dangling pointer is more like pointing to Neil then making him leave his chair without changing where you're pointing...then trying to follow that pointer and interpreting what you find there as a Neil regardless of who's ended up there.
    – Jon Purdy
    Mar 12, 2011 at 19:47
11

I really get quite worried when I hear the "how did you get a grasp on pointers" question. I always thought the concept was incredibly simple, and a logical evolution of languages providing great power to the programmers.

The thing which worries me is that I never found it difficult to understand the concept of pointers. So when you here "when did you finally get it" over and over again, you start thinking:

Do I actually get it? Maybe I never did?

Maybe the reason why the concept seems to be a tricky one, is because we keep telling everyone who has yet to encounter them that pointers are so difficult, and here are a hundred ways in which you can learn?

Just throwing that idea out there, of course personally I love a good diagram and Steve Gibson always does a fantastic job of explaining anything!

5
  • Interesting... which language did you use at the time? I think the C syntax trips up a lot of people. If you knew assembly first I could see that being one reason. [BTW, I want to vote this up, but I reached my cap for today.]
    – Macneil
    Nov 11, 2010 at 15:13
  • Interestingly enough, I had no knowledge of "dangerous" pointers for a long time, working in Python (and Java at University). Then I took an "object oriented methods" module which used C++ as the language of choice and dove straight in there. Nov 11, 2010 at 22:35
  • Also I think having an understanding of how a program is represented in memory can definitely help, but I think I would rather say that understanding why pointers were a useful addition to a language, is the most effective angle, since you are undergoing the same though process as the original designers. Nov 11, 2010 at 22:44
  • +1 I have no idea why people think pointers are hard or mysterious.
    – ggambetta
    Mar 12, 2011 at 18:35
  • Yeah, pointers have always been so obviously simple and useful that I can't imagine thinking there's anything "hard" about them. I hate it when a teacher of any course says "now, this is a bit tricky" because it's just so subversive. Just teach the damn stuff, and let the students decide for themselves whether they think it's tricky.
    – Jon Purdy
    Mar 12, 2011 at 19:51
7

I never had much of a problem with pointers in C, but that may be because I had to learn assembler first. It was actually a relief not to have to manage addresses myself any more. So maybe the answer (assuming this is something you're teaching) is to give students an emulated assembly language to work with. They will figure it out in the process of writing anything more sophisticated than "Hello, world."

3
  • +1 for adapting a more primitive abstraction, rather than trying to use an analogy. Nov 9, 2010 at 23:37
  • In my high school, one unit of Computer Studies was devoted to studying a matchbox computer, which can be taught from the blackboard without ever touching or involving a real computer.
    – rwong
    Nov 10, 2010 at 5:15
  • @Larry Coleman, Assembly!!!!!!!!!!! I want to try it first before C. Please tell me where to start learning. Free Ebooks, Free PDF? IDE? Please!!!!!!!!!!!!!!!!!!! Oct 17, 2012 at 9:49
7

How I really learned about pointers? By writing a simple compiler freshmen year of college.

How to explain pointers in layman's terms? I like the (dated?) analogy of a library catalog stored on index cards. Each card ("pointer") contains information about where some book ("data") is located, but doesn't actually contain the book itself. If you modify the card ("pointer arithmetic"), all it does is change what book it points to and has no impact on the book itself - just be careful not to screw up the address or you might point to a non-existent book or even the wrong library. However, if you follow the "address" on the card and go to the proper part of the library ("dereference the pointer"), you can see/modify the book itself.

3
  • +1 for the memory of my CS course where I had exactly that explanation
    – Gary
    Nov 9, 2010 at 21:16
  • That's good in a way, but somewhat misleading, as the cards don't actually say where the book is. You still need to execute a sneaker-oriented search algorithm. Maybe this better models a database - refering to a stored object by a key (call number).
    – DarenW
    Nov 16, 2010 at 7:27
  • +1 The analogy is retains the same concept as the one explained by Barfieldmv but with a more real life approach. Mar 7, 2012 at 6:33
7

A pointer is a variable whose value is the memory address of another variable.

2
  • Elegant, why make it more complicated. Nov 10, 2010 at 16:15
  • If pointers don't seem immediately intuitive and useful, they've been explained wrong.
    – Jon Purdy
    Nov 11, 2010 at 9:31
5

I shall assume someone going to learn pointers knows what the normal variables are and how they work in C. Now, let's try to define pointers with some of it's attributes-

  • They are also variables, but of different nature. Assume there are two layers in the variable space. The normal variables of different types resides in the upper layer and pointers in the lower layer. Like this figure-

    alt text

  • As the name 'Pointer' suggests, pointers can POINT to something. Like our finger can point to some object. What are the things they point to? These are the normal variables. In short, "Pointers point to normal variables".

  • Like normal variables, pointers also are of same number of types like int,char or float. And a pointer of a specific type can point to only same type of variables.
  • A pointer can point to one variable and later the same pointer can point to another variable. Just the type should be same. So, the a pointer's association with some variable is not permanent and can be changed.
  • So, how a pointer is declared? Almost like normal variables. You have to precede the name with an asterisk(*). Like-

    int *pointer;
    
  • Then, how a pointer is associated with a variable? Using the & operator before the variable like this statement-

    pointer = &variable;
    
  • How a pointer is used by pointing to a variable? This is also done by preceding the name with an asterisk(*). Then it can be used in the place of the variable it's pointing now-

    *pointer = var1 + var2;
    

    instead of

    variable = var1 + var2;
    
  • Now, play with pointers with some code. Just get used to this characteristics of pointers now. Upto this point, we are talking about what pointers do. Once you are ok with it, then start studying how pointers are pointing to some variable and how they react if normal arithmetic operations are applied on them. Then go for the relation between pointers and arrays and pointers to pointers.

That is all I shall suggest about learning pointers.

1
  • I wanted to follow "first what it does then how" process. Abstraction!
    – Gulshan
    Nov 10, 2010 at 6:44
5

Edited in support of the revised requirement of the question

My path to "post-pointer" understanding (if I recall correctly) went like this. I had some simple experience of assembly programming from when I was still mucking around with a BBC Micro so I had the concept of memory as a bunch of boxes (see below for this). This was reinforced by the use of arrays. However, I was going into the world of C and had to deal with strings and that meant pointers. In BASIC this was trivial, in assembler I never had to work with them, and now in classic C it's all pointers and stuff. Ah, but I can scuttle back to arrays with (null terminated) strings like this:

char s[] = "Hello, world!";
printf("%s",s);

All well and good, that's just an array of chars (8 bits per character in my little world) with a zero character at the end to show where it ends. The printf just takes that array and runs over it printing it. But what if I want to pass this string into a function?

void print_str(char* p) {
  printf("%s",p);
}

Is what the manual says, but what's that * all about? Hmm, char* means "pointer to a char". OK... lost me. Then it dawned on me that the char* makes p equivalent to s[0]. OK, I can use that, but I still haven't twigged what pointers are. I mean, how do I set some data with one of these things? Off to the manual again...

char* p = "Hello World!";

As I write the above I'm saying to myself "declare a pointer to a char and set it equal to this array of characters". Somehow that pointer does away with the need for an array. Guess it's the compiler doing some stuff for me for a change. So how can I change the array with this pointer? I know that I could use the array version

 s[2] = 'L'; 

but what's the equivalent in "pointer speak"? Off to that manual again...

*(p+2) = 'L';

I suppose that * simply means "the contents of the memory address" and (p+2) is s[2]. Which meant that the pointer p was... just... an... address... bong!

That there is the sound of enlightenment. I suddenly twigged pointers (it was a long time ago, we old timers didn't "grok" until later). It was just indirection.


Original:

OK, my 2c worth:

Imagine memory is a bunch of boxes. Each box has a number on the side (the address). Each box contains a number (the contents). You can work with these boxes in 2 ways: variables (I want the contents of box N), pointers (I want the contents of box whatever is in box N ). Pointers are simply indirection.

And for the big answer that covers everything you will ever need to know - read this.

7
  • ++ That's more or less the way I taught the subject. Nov 9, 2010 at 21:04
  • Edited article to support OP requirements.
    – Gary
    Nov 12, 2010 at 12:19
  • Which manual were you using that added extra NUL characters at the end of your strings? Nov 15, 2010 at 9:53
  • @raimesh A very old one (around 1991). Can't remember which.
    – Gary
    Nov 15, 2010 at 10:28
  • 1991? That's not old for a C language manual - the 1st edition of K&R was published in 1978! Just intrigued that there was ever a manual out there that suggested you needed to put \0 at the end of your string constants. (Actually, looking at it again, did you mean to put \n?) Nov 21, 2010 at 12:33
4

Get some little blocks of wood.

add metal hooks to one end, and metal eyes to the other.

you can now do a linked list in stuff you can play with.

Try explaining with this physical prop. I often wished I had this when teaching pointers to first year ( freshmen) students.

The little metal hook is the pointer, the block of wood the thing pointed to.

I DEFY anyone to not get it after playing with the blocks.

4

I made my life easier when I just removed all the fluff and started treating pointer as any other variable rather than some magical entity (long long ago in grade 11).. just know 3 things:

  1. Pointer is a variable that store the address of another variable (or just any address).
  2. * is used to get the value at the memory location that is stored in the pointer variable.
  3. & operator gives the address of a memory location.

The rest is syntactic sugar and common sense.. Just write some simple C programs (like implementing a linked list library) using pointers to get a hang of it.

2
  1. Pointer can be thought of as a generalization of an index into an array.
    • Consider that a big array can be chopped off into a number of smaller, non-overlapping, variable-sized arrays. Now, these smaller arrays are what we usually think of as array. The bigger one is then the computer's entire memory space. The process of chopping off smaller arrays is called memory allocation.
  2. A set of structures which are linked together by some pointers can be thought of as a directed graph.
    • Each vertex is a variable which can hold some value.
    • Some variables are pointers, and each pointer can have exactly one outgoing edge into something else.
    • Variables which are not pointers will not have any outgoing edge. They could have any number of incoming edge.
2

I cant quite remember the circumstances around my pointers-aha-moment, but I have retroactively refitted the memory around my understanding of a c-style array. (i.e. arr[3] is the same as *(arr+3) )

For some reason I find it immensely helpful to view pointers as arrays whenever I happen upon a pointer-situation.

2

Basically @Gary Rowe introduced the right model. Memory as a set of boxes with addresses (numbers) on them. Each box stores a value (number).

The idea of a pointer is to interpret the value in one box as the address of another box. This value is used to refer to a specific box, which is why it is called a reference. Thus dereferencing is the process of opening the box that is refered to.

if v is a variable (box), then the statement

  • v means value of v, i.e. give me what is in the box
  • *v means dereference the value of v, i.e. give me what is in the box refered to by the value of v
  • &v means reference v, i.e. give me the address on box

I think it doesn't server the purpose of introducing pointers as something completely different. It was a concept hard to grasp for me when I was a kid. It always seemed like some dark magic I never truly understood, that needed a lot of special characters. The first time I did understand was when I wrote a small game using double indirection in a language that doesn't have pointer arithmetics. That enlightened me.

Pointers are a matter of interpretation. I think explaining that makes things a lot easier. And pointer arithmetics are extremely simple and intuitive operations if shown a simple example with a memory of 10 variables.

2

The explanation that i really grocked was:

Consider a city grid with different houses built on pieces of land. In your hand you hold a piece of paper. On the paper you have written:


David's house,

112 So and so street.


The piece of paper (pointer variable) contains an address that points to David's house. When you want to tell a friend to have a look at David's cool house it is much easier to use the pice of paper as a reference to the house than to send the actual two story building in the mail.

As with real pointers you can get into some trouble when you follow the address on your piece of paper. David could have moved and when you get there you just find a big hole in the ground. In this case it would have been better to erase the address on the paper when David moved or at least change it to the new one. You could also find that you go to the address and enter what you think is your friend David's living room but this time you end up in a complete strangers swimming pool. Someone else has used the space at the address you had for something completely different.

2

If you want to explain pointers you have to explain memory first. I usually do that using graph paper/squared paper with rows and columns. If the "student" understands memory she can understand what an address is. If you got address you got pointers.

You can play with this abstraction. E.g. write the address (number) of one square into another square. Now draw an arrow from the pointer square to the destination square. Now overwrite the pointer (e.g. increment it) and adjust the arrow. Write an address into another square and let the student draw the arrow...

Next step: Give certain squares (like the pointer) a name. Now you can explain dereferencing. That's it.

1
  • 2
    Reminds me of a "computer" I used before I could get my hands on one that actually used electrons - the cardboard "CARDIAC" I think it was called. Literally, writing numbers in numbered boxes to get numbers from other numbered boxes. It was educational and I never had trouble understanding pointers on real microprocessors.
    – DarenW
    Nov 16, 2010 at 7:17
2

Perhaps it's just me, but I work well with analogies. So let's say you have a friend (function/class) "Foo", who wants to have someone else (different function/class), "Bar", contact you for some reason. "Foo" could take you to go see "Bar", but that's not convenient, moving all those beings (instances) around. However, "Foo" could send "Bar" your phone number (pointer). That way, no matter where you are, "Foo" knows how to contact you without having to find you.

And, let's say "Bar" has an acquaintance, "Baz", who also wants to get in touch with you. But you're protective of your phone number and you don't want everyone to have, "Baz" can call "Bar" (phone as pointer), who can then forward the call to you (another pointer). And so on and on down the chain of "Baz"'s friends and friends of friends.

2

Pointers make way more sense if you've studied assembly language and/or computer architecture. I think that if I teach a C class, I would start with a couple weeks of architecture to explain the memory model and the kinds of instructions the processor actually executes.

1
  • Absolutely. When you deal with registers, and understand things like immediate values and indirect addressing, the whole concept of pointers is intuitive. I learned 6502 assembly and then 68K assembly before writing my first line of C, so by the time I was introduced to pointers, I looked at the compiler's (intermediate) assembly and it was exactly as expected.
    – Radian
    Oct 18, 2011 at 18:17
2

My "aha!" moment came in this tutorial:

A Tutorial on Pointers and Arrays in C

To be exact, it came in this chapter: Chapter 3: Pointers and Strings

To be even more precise, it came with this sentence:

The parameter passed to puts() is a pointer, that is the value of a pointer (since all parameters in C are passed by value), and the value of a pointer is the address to which it points, or, simply, an address.

When I read that, the clouds parted and angels blew trumpet fanfares.

For, you see, every C tutorial or book I'd read prior to that had asserted that C could pass by value or by reference, a nefarious lie. The truth is that C always passes by value, but sometimes the value passed happens to be an address. Within the method, a copy is made of that address, just like a copy would be made of an int passed in. A copy is not made of the value to which the pointer points. Thus by using the pointer within the method you can access the original value and change it.

I never became a C programmer, but I became a .NET programmer, and objects and object references work the same way; the reference to the object is passed by value (and thus copied), but the object itself isn't copied. I've worked around many programmers who don't understand this because they never learned pointers.

1

The trick is to explain that the location of a thing and the thing itself are not the same, just like a picture of a pipe is not a pipe. When you move a thing, its location changes. The location remains and some other thing can be put there.

1

A pointer is a sticky note that tells you where something useful is. It contains the location of the thing and tells you how big the thing is (in C, anyway). So a double pointer is like a sticky note that says "There's a six pack in the fridge". You have to actually go get the six pack to figure out if it's Coke or Budweiser.

1

Given the code :

int v=42; // declaring and initializing a simple variable

int *p = &v; // creating a point p to the variable v

Following can be said about the above code:

int * p // "int pointer p" ... this is how you declare a pointer to variable of type int

*p // "pointed to by p" ... that is the data that p points to, its same as v.

&v // "address of the variable v" ... this represents the literal value for p

1

http://cslibrary.stanford.edu/

This site has great tutorials for learning pointers and memory management .

I would suggest you to walk through pointers basics, pointers and memory given on the site. You can also look at linked lists problems given on the link to further strengthen the pointer concepts.

1

The key to explaining pointers is making sure that the people you are explaining to, already have an understanding of the concept of memory. Whilst it would be nice if they really understood it low level, believing that memory exists as a massive array, and understanding that you can access any position in the array by its index location is enough.

The next step, having the concept of passing the index location rather than copying the entire memory makes sense to most people. And that is enough to allow most people to understand why pointers are useful.

the final step to understand pointers is to explain how you can pass in as a parameter a memory index location for the method to store the index location for where all the data is stored. I have found that this can be step too far for some people to cope with.

Once someone has grasped these basic steps its straight forward for them to grasp that you can chain pointers indefinitely, just as long as you keep track of how many times you need to look at addresses to find the actual data object.

Once someone has grasped pointers, the next thing that they must grasp quickly is the difference between heap memory and stack memory, and why pointers to stack memory are dangerous when passed outside the method.

0

I remember a book "C puzzles" or similar, which I read purely because it was one of the few programming/computer related books available in the library, my understanding of C was rudimentary. It threw a C expresison at you, and asked to explion it, getting more and more complicated.

0

When I was in university, my professor had some really neat powerpoint slides depicting a point as a separate variable on it's own with an arrow to a memory location (represented like an array) and when we were doing Linked Lists, he would do it step-by-step, showing when the arrow changes, when the pointer is dereferenced etc..., there was no way one could not understand it within a couple of minutes. The concept itself is really easy, but doing it right or applying it in practical programs requires more practice.

0

Before I do that, I explain that in programming "everything uses memory", and (static) variable allocation in memory. I will also explain what a memory address is, and the relation between memory space, memory address and variables.

Finally, I explain that there are integer data type and variables, string data type and variables... and so on, until explaining that there are an special data type that stores memory addresses, that has an empty value like 0 o "", called null.

And, finally, dynamically allocated variables thru the usage of pointers.

Not the answer you're looking for? Browse other questions tagged or ask your own question.