<p>Why are pointers such a leading factor of confusion for many new, and even old, college level students in C or C++?  Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?</p>

<p>What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios.</p>

[{'answer_id': 5728, 'author': 'Josh', 'author_id': 257, 'author_profile': 'https://Stackoverflow.com/users/257', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n  <p>Why are pointers such a leading factor of confusion for many new, and even old, college level students in the C/C++ language? </p>\n</blockquote>\n\n<p>The concept of a placeholder for a value - variables - maps onto something we\'re taught in school - algebra.  There isn\'t an existing parallel you can draw without understanding how memory is physically laid out within a computer, and no one thinks about this kind of thing until they\'re dealing with low level things - at the C/C++/byte communications level.</p>\n\n<blockquote>\n  <p>Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?</p>\n</blockquote>\n\n<p>Addresses boxes.  I remember when I was learning to program BASIC into microcomputers, there were these pretty books with games in them, and sometimes you had to poke values into particular addresses.  They had a picture of a bunch of boxes, incrementally labelled with 0, 1, 2... and it was explained that only one small thing (a byte) could fit in these boxes, and there were a lot of them - some computers had as many as 65535!  They were next to each other, and they all had an address.</p>\n\n<blockquote>\n  <p>What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios.</p>\n</blockquote>\n\n<p>For a drill?  Make a struct:</p>\n\n<pre class="lang-cpp prettyprint-override"><code>struct {\nchar a;\nchar b;\nchar c;\nchar d;\n} mystruct;\nmystruct.a = \'r\';\nmystruct.b = \'s\';\nmystruct.c = \'t\';\nmystruct.d = \'u\';\n\nchar* my_pointer;\nmy_pointer = &amp;mystruct.b;\ncout &lt;&lt; \'Start: my_pointer = \' &lt;&lt; *my_pointer &lt;&lt; endl;\nmy_pointer++;\ncout &lt;&lt; \'After: my_pointer = \' &lt;&lt; *my_pointer &lt;&lt; endl;\nmy_pointer = &amp;mystruct.a;\ncout &lt;&lt; \'Then: my_pointer = \' &lt;&lt; *my_pointer &lt;&lt; endl;\nmy_pointer = my_pointer + 3;\ncout &lt;&lt; \'End: my_pointer = \' &lt;&lt; *my_pointer &lt;&lt; endl;\n</code></pre>\n\n<p>Same example as above, except in C:</p>\n\n<pre class="lang-c prettyprint-override"><code>// Same example as above, except in C:\nstruct {\n    char a;\n    char b;\n    char c;\n    char d;\n} mystruct;\n\nmystruct.a = \'r\';\nmystruct.b = \'s\';\nmystruct.c = \'t\';\nmystruct.d = \'u\';\n\nchar* my_pointer;\nmy_pointer = &amp;mystruct.b;\n\nprintf("Start: my_pointer = %c\\n", *my_pointer);\nmy_pointer++;\nprintf("After: my_pointer = %c\\n", *my_pointer);\nmy_pointer = &amp;mystruct.a;\nprintf("Then: my_pointer = %c\\n", *my_pointer);\nmy_pointer = my_pointer + 3;\nprintf("End: my_pointer = %c\\n", *my_pointer);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Start: my_pointer = s\nAfter: my_pointer = t\nThen: my_pointer = r\nEnd: my_pointer = u\n</code></pre>\n\n<p>Perhaps that explains some of the basics through example?</p>\n'}, {'answer_id': 5734, 'author': 'Matt Mitchell', 'author_id': 364, 'author_profile': 'https://Stackoverflow.com/users/364', 'pm_score': 3, 'selected': False, 'text': "<p>I don't think pointers as a concept are particularly tricky - most students' mental models map to something like this and some quick box sketches can help.</p>\n\n<p>The difficulty, at least that which I've experienced in the past and seen others deal with, is that the management of pointers in C/C++ can be unncessarily convoluted.</p>\n"}, {'answer_id': 5735, 'author': 'grom', 'author_id': 486, 'author_profile': 'https://Stackoverflow.com/users/486', 'pm_score': 0, 'selected': False, 'text': "<p>I don't see what is so confusing about pointers. They point to a location in memory, that is it stores the memory address. In C/C++ you can specify the type the pointer points to. For example:</p>\n\n<pre><code>int* my_int_pointer;\n</code></pre>\n\n<p>Says that my_int_pointer contains the address to a location that contains an int.</p>\n\n<p>The problem with pointers is that they point to a location in memory, so it is easy to trail off into some location you should not be in. As proof look at the numerous security holes in C/C++ applications from buffer overflow (incrementing the pointer past the allocated boundary).</p>\n"}, {'answer_id': 5736, 'author': 'JSN', 'author_id': 108465, 'author_profile': 'https://Stackoverflow.com/users/108465', 'pm_score': 6, 'selected': False, 'text': "<p>The reason pointers seem to confuse so many people is that they mostly come with little or no background in computer architecture. Since many don't seem to have an idea of how computers (the machine) is actually implemented - working in C/C++ seems alien.</p>\n\n<p>A drill is to ask them to implement a simple bytecode based virtual machine (in any language they chose, python works great for this) with an instruction set focussed on pointer operations (load, store, direct/indirect addressing). Then ask them to write simple programs for that instruction set.</p>\n\n<p>Anything requiring slightly more than simple addition is going to involve pointers and they are sure to get it.</p>\n"}, {'answer_id': 5750, 'author': 'Mike Minutillo', 'author_id': 358, 'author_profile': 'https://Stackoverflow.com/users/358', 'pm_score': 2, 'selected': False, 'text': "<p>I think that the main reason that people have trouble with it is because it's generally not taught in an interesting and engaging manner. I'd like to see a lecturer get 10 volunteers from the crowd and give them a 1 meter ruler each, get them to stand around in a certain configuration and use the rulers to point at each other. Then show pointer arithmetic by moving people around (and where they point their rulers). It'd be a simple but effective (and above all memorable) way of showing the concepts without getting too bogged down in the mechanics.</p>\n\n<p>Once you get to C and C++ it seems to get harder for some people. I'm not sure if this is because they are finally putting theory that they don't properly grasp into practice or because pointer manipulation is inherently harder in those languages. I can't remember my own transition that well, but I <strong>knew</strong> pointers in Pascal and then moved to C and got totally lost.</p>\n"}, {'answer_id': 5754, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 11, 'selected': True, 'text': '<p>Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block.</p>\n\n<p>I\'ve found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the actual house. All sorts of operations can thus be easily explained.</p>\n\n<p>I\'ve added some Delphi code down below, and some comments where appropriate. I chose Delphi since my other main programming language, C#, does not exhibit things like memory leaks in the same way.</p>\n\n<p>If you only wish to learn the high-level concept of pointers, then you should ignore the parts labelled "Memory layout" in the explanation below. They are intended to give examples of what memory could look like after operations, but they are more low-level in nature. However, in order to accurately explain how buffer overruns really work, it was important that I added these diagrams.</p>\n\n<p><em>Disclaimer: For all intents and purposes, this explanation and the example memory\nlayouts are vastly simplified. There\'s more overhead and a lot more details you would\nneed to know if you need to deal with memory on a low-level basis. However, for the\nintents of explaining memory and pointers, it is accurate enough.</em></p>\n\n<hr>\n\n<p>Let\'s assume the THouse class used below looks like this:</p>\n\n<pre><code>type\n    THouse = class\n    private\n        FName : array[0..9] of Char;\n    public\n        constructor Create(name: PChar);\n    end;\n</code></pre>\n\n<p>When you initialize the house object, the name given to the constructor is copied into the private field FName. There is a reason it is defined as a fixed-size array.</p>\n\n<p>In memory, there will be some overhead associated with the house allocation, I\'ll illustrate this below like this:</p>\n\n<pre>\n---[ttttNNNNNNNNNN]---\n     ^   ^\n     |   |\n     |   +- the FName array\n     |\n     +- overhead\n</pre>\n\n<p>The "tttt" area is overhead, there will typically be more of this for various types of runtimes and languages, like 8 or 12 bytes. It is imperative that whatever values are stored in this area never gets changed by anything other than the memory allocator or the core system routines, or you risk crashing the program.</p>\n\n<hr>\n\n<p><strong>Allocate memory</strong></p>\n\n<p>Get an entrepreneur to build your house, and give you the address to the house. In contrast to the real world, memory allocation cannot be told where to allocate, but will find a suitable spot with enough room, and report back the address to the allocated memory.</p>\n\n<p>In other words, the entrepreneur will choose the spot.</p>\n\n<pre><code>THouse.Create(\'My house\');\n</code></pre>\n\n<p>Memory layout:</p>\n\n<pre>\n---[ttttNNNNNNNNNN]---\n    1234My house\n</pre>\n\n<hr>\n\n<p><strong>Keep a variable with the address</strong></p>\n\n<p>Write the address to your new house down on a piece of paper. This paper will serve as your reference to your house. Without this piece of paper, you\'re lost, and cannot find the house, unless you\'re already in it.</p>\n\n<pre><code>var\n    h: THouse;\nbegin\n    h := THouse.Create(\'My house\');\n    ...\n</code></pre>\n\n<p>Memory layout:</p>\n\n<pre>\n    h\n    v\n---[ttttNNNNNNNNNN]---\n    1234My house\n</pre>\n\n<hr>\n\n<p><strong>Copy pointer value</strong>  </p>\n\n<p>Just write the address on a new piece of paper. You now have two pieces of paper that will get you to the same house, not two separate houses. Any attempts to follow the address from one paper and rearrange the furniture at that house will make it seem that <em>the other house</em> has been modified in the same manner, unless you can explicitly detect that it\'s actually just one house.</p>\n\n<p><em>Note</em> This is usually the concept that I have the most problem explaining to people, two pointers does not mean two objects or memory blocks.</p>\n\n<pre><code>var\n    h1, h2: THouse;\nbegin\n    h1 := THouse.Create(\'My house\');\n    h2 := h1; // copies the address, not the house\n    ...\n</code></pre>\n\n<pre>\n    h1\n    v\n---[ttttNNNNNNNNNN]---\n    1234My house\n    ^\n    h2\n</pre>\n\n<hr>\n\n<p><strong>Freeing the memory</strong>  </p>\n\n<p>Demolish the house. You can then later on reuse the paper for a new address if you so wish, or clear it to forget the address to the house that no longer exists.</p>\n\n<pre><code>var\n    h: THouse;\nbegin\n    h := THouse.Create(\'My house\');\n    ...\n    h.Free;\n    h := nil;\n</code></pre>\n\n<p>Here I first construct the house, and get hold of its address. Then I do something to the house (use it, the ... code, left as an exercise for the reader), and then I free it. Lastly I clear the address from my variable.</p>\n\n<p>Memory layout:</p>\n\n<pre>\n    h                        &lt;--+\n    v                           +- before free\n---[ttttNNNNNNNNNN]---          |\n    1234My house             &lt;--+\n\n    h (now points nowhere)   &lt;--+\n                                +- after free\n----------------------          | (note, memory might still\n    xx34My house             &lt;--+  contain some data)\n</pre>\n\n<hr>\n\n<p><strong>Dangling pointers</strong></p>\n\n<p>You tell your entrepreneur to destroy the house, but you forget to erase the address from your piece of paper. When later on you look at the piece of paper, you\'ve forgotten that the house is no longer there, and goes to visit it, with failed results (see also the part about an invalid reference below).</p>\n\n<pre><code>var\n    h: THouse;\nbegin\n    h := THouse.Create(\'My house\');\n    ...\n    h.Free;\n    ... // forgot to clear h here\n    h.OpenFrontDoor; // will most likely fail\n</code></pre>\n\n<p>Using <code>h</code> after the call to <code>.Free</code> <em>might</em> work, but that is just pure luck. Most likely it will fail, at a customers place, in the middle of a critical operation.</p>\n\n<pre>\n    h                        &lt;--+\n    v                           +- before free\n---[ttttNNNNNNNNNN]---          |\n    1234My house             &lt;--+\n\n    h                        &lt;--+\n    v                           +- after free\n----------------------          |\n    xx34My house             &lt;--+\n</pre>\n\n<p>As you can see, h still points to the remnants of the data in memory, but\nsince it might not be complete, using it as before might fail.</p>\n\n<hr>\n\n<p><strong>Memory leak</strong>  </p>\n\n<p>You lose the piece of paper and cannot find the house. The house is still standing somewhere though, and when you later on want to construct a new house, you cannot reuse that spot.</p>\n\n<pre><code>var\n    h: THouse;\nbegin\n    h := THouse.Create(\'My house\');\n    h := THouse.Create(\'My house\'); // uh-oh, what happened to our first house?\n    ...\n    h.Free;\n    h := nil;\n</code></pre>\n\n<p>Here we overwrote the contents of the <code>h</code> variable with the address of a new house, but the old one is still standing... somewhere. After this code, there is no way to reach that house, and it will be left standing. In other words, the allocated memory will stay allocated until the application closes, at which point the operating system will tear it down.</p>\n\n<p>Memory layout after first allocation:</p>\n\n<pre>\n    h\n    v\n---[ttttNNNNNNNNNN]---\n    1234My house\n</pre>\n\n<p>Memory layout after second allocation:</p>\n\n<pre>\n                       h\n                       v\n---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN]\n    1234My house       5678My house\n</pre>\n\n<p>A more common way to get this method is just to forget to free something, instead of overwriting it as above. In Delphi terms, this will occur with the following method:</p>\n\n<pre><code>procedure OpenTheFrontDoorOfANewHouse;\nvar\n    h: THouse;\nbegin\n    h := THouse.Create(\'My house\');\n    h.OpenFrontDoor;\n    // uh-oh, no .Free here, where does the address go?\nend;\n</code></pre>\n\n<p>After this method has executed, there\'s no place in our variables that the address to the house exists, but the house is still out there.</p>\n\n<p>Memory layout:</p>\n\n<pre>\n    h                        &lt;--+\n    v                           +- before losing pointer\n---[ttttNNNNNNNNNN]---          |\n    1234My house             &lt;--+\n\n    h (now points nowhere)   &lt;--+\n                                +- after losing pointer\n---[ttttNNNNNNNNNN]---          |\n    1234My house             &lt;--+\n</pre>\n\n<p>As you can see, the old data is left intact in memory, and will not\nbe reused by the memory allocator. The allocator keeps track of which\nareas of memory has been used, and will not reuse them unless you\nfree it.</p>\n\n<hr>\n\n<p><strong>Freeing the memory but keeping a (now invalid) reference</strong>  </p>\n\n<p>Demolish the house, erase one of the pieces of paper but you also have another piece of paper with the old address on it, when you go to the address, you won\'t find a house, but you might find something that resembles the ruins of one.</p>\n\n<p>Perhaps you will even find a house, but it is not the house you were originally given the address to, and thus any attempts to use it as though it belongs to you might fail horribly.</p>\n\n<p>Sometimes you might even find that a neighbouring address has a rather big house set up on it that occupies three address (Main Street 1-3), and your address goes to the middle of the house. Any attempts to treat that part of the large 3-address house as a single small house might also fail horribly.</p>\n\n<pre><code>var\n    h1, h2: THouse;\nbegin\n    h1 := THouse.Create(\'My house\');\n    h2 := h1; // copies the address, not the house\n    ...\n    h1.Free;\n    h1 := nil;\n    h2.OpenFrontDoor; // uh-oh, what happened to our house?\n</code></pre>\n\n<p>Here the house was torn down, through the reference in <code>h1</code>, and while <code>h1</code> was cleared as well, <code>h2</code> still has the old, out-of-date, address. Access to the house that is no longer standing might or might not work.</p>\n\n<p>This is a variation of the dangling pointer above. See its memory layout.</p>\n\n<hr>\n\n<p><strong>Buffer overrun</strong>  </p>\n\n<p>You move more stuff into the house than you can possibly fit, spilling into the neighbours house or yard. When the owner of that neighbouring house later on comes home, he\'ll find all sorts of things he\'ll consider his own.</p>\n\n<p>This is the reason I chose a fixed-size array. To set the stage, assume that\nthe second house we allocate will, for some reason, be placed before the\nfirst one in memory. In other words, the second house will have a lower\naddress than the first one. Also, they\'re allocated right next to each other.</p>\n\n<p>Thus, this code:</p>\n\n<pre><code>var\n    h1, h2: THouse;\nbegin\n    h1 := THouse.Create(\'My house\');\n    h2 := THouse.Create(\'My other house somewhere\');\n                         ^-----------------------^\n                          longer than 10 characters\n                         0123456789 &lt;-- 10 characters\n</code></pre>\n\n<p>Memory layout after first allocation:</p>\n\n<pre>\n                        h1\n                        v\n-----------------------[ttttNNNNNNNNNN]\n                        5678My house\n</pre>\n\n<p>Memory layout after second allocation:</p>\n\n<pre>\n    h2                  h1\n    v                   v\n---[ttttNNNNNNNNNN]----[ttttNNNNNNNNNN]\n    1234My other house somewhereouse\n                        ^---+--^\n                            |\n                            +- overwritten\n</pre>\n\n<p>The part that will most often cause crash is when you overwrite important parts\nof the data you stored that really should not be randomly changed. For instance\nit might not be a problem that parts of the name of the h1-house was changed,\nin terms of crashing the program, but overwriting the overhead of the\nobject will most likely crash when you try to use the broken object,\nas will overwriting links that is stored to\nother objects in the object.</p>\n\n<hr>\n\n<p><strong>Linked lists</strong>  </p>\n\n<p>When you follow an address on a piece of paper, you get to a house, and at that house there is another piece of paper with a new address on it, for the next house in the chain, and so on.</p>\n\n<pre><code>var\n    h1, h2: THouse;\nbegin\n    h1 := THouse.Create(\'Home\');\n    h2 := THouse.Create(\'Cabin\');\n    h1.NextHouse := h2;\n</code></pre>\n\n<p>Here we create a link from our home house to our cabin. We can follow the chain until a house has no <code>NextHouse</code> reference, which means it\'s the last one. To visit all our houses, we could use the following code:</p>\n\n<pre><code>var\n    h1, h2: THouse;\n    h: THouse;\nbegin\n    h1 := THouse.Create(\'Home\');\n    h2 := THouse.Create(\'Cabin\');\n    h1.NextHouse := h2;\n    ...\n    h := h1;\n    while h &lt;&gt; nil do\n    begin\n        h.LockAllDoors;\n        h.CloseAllWindows;\n        h := h.NextHouse;\n    end;\n</code></pre>\n\n<p>Memory layout (added NextHouse as a link in the object, noted with\nthe four LLLL\'s in the below diagram):</p>\n\n<pre>\n    h1                      h2\n    v                       v\n---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL]\n    1234Home       +        5678Cabin      +\n                   |        ^              |\n                   +--------+              * (no link)\n</pre>\n\n<hr>\n\n<p><strong>In basic terms, what is a memory address?</strong></p>\n\n<p>A memory address is in basic terms just a number. If you think of memory\nas a big array of bytes, the very first byte has the address 0, the next one\nthe address 1 and so on upwards. This is simplified, but good enough.</p>\n\n<p>So this memory layout:</p>\n\n<pre>\n    h1                 h2\n    v                  v\n---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN]\n    1234My house       5678My house\n</pre>\n\n<p>Might have these two address (the leftmost - is address 0):</p>\n\n<ul>\n<li>h1 = 4</li>\n<li>h2 = 23</li>\n</ul>\n\n<p>Which means that our linked list above might actuall look like this:</p>\n\n<pre>\n    h1 (=4)                 h2 (=28)\n    v                       v\n---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL]\n    1234Home      0028      5678Cabin     0000\n                   |        ^              |\n                   +--------+              * (no link)\n</pre>\n\n<p>It is typical to store an address that "points nowhere" as a zero-address.</p>\n\n<hr>\n\n<p><strong>In basic terms, what is a pointer?</strong></p>\n\n<p>A pointer is just a variable holding a memory address. You can typically ask the programming\nlanguage to give you its number, but most programming languages and runtimes tries to\nhide the fact that there is a number beneath, just because the number itself does not\nreally hold any meaning to you. It is best to think of a pointer as a black box, ie.\nyou don\'t really know or care about how it is actually implemented, just as long as it\nworks.</p>\n'}, {'answer_id': 5772, 'author': 'David', 'author_id': 381, 'author_profile': 'https://Stackoverflow.com/users/381', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.augustcouncil.com/~tgibson/tutorial/ptr.html" rel="noreferrer">An example of a tutorial with a good set of diagrams helps greatly with the understanding of pointers</a>. </p>\n\n<p>Joel Spolsky makes some good points about understanding pointers in his <a href="http://www.joelonsoftware.com/articles/fog0000000073.html" rel="noreferrer">Guerrilla Guide to Interviewing</a> article:</p>\n\n<blockquote>\n  <p>For some reason most people seem to be born without the part of the brain that understands pointers. This is an aptitude thing, not a skill thing – it requires a complex form of doubly-indirected thinking that some people just can\'t do.</p>\n</blockquote>\n'}, {'answer_id': 6416, 'author': 'Tryke', 'author_id': 773, 'author_profile': 'https://Stackoverflow.com/users/773', 'pm_score': 7, 'selected': False, 'text': '<p>In my first Comp Sci class, we did the following exercise. Granted, this was a lecture hall with roughly 200 students in it...</p>\n\n<p>Professor writes on the board: <code>int john;</code></p>\n\n<p>John stands up</p>\n\n<p>Professor writes: <code>int *sally = &amp;john;</code></p>\n\n<p>Sally stands up, points at john</p>\n\n<p>Professor: <code>int *bill = sally;</code></p>\n\n<p>Bill stands up, points at John</p>\n\n<p>Professor: <code>int sam;</code></p>\n\n<p>Sam stands up</p>\n\n<p>Professor: <code>bill = &amp;sam;</code></p>\n\n<p>Bill now points to Sam.</p>\n\n<p>I think you get the idea. I think we spent about an hour doing this, until we went over the basics of pointer assignment.</p>\n'}, {'answer_id': 7271, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 4, 'selected': False, 'text': "<p>The complexities of pointers go beyond what we can easily teach.  Having students point to each other and using pieces of paper with house addresses are both great learning tools.  They do a great job of introducing the basic concepts.  Indeed, learning the basic concepts is <em>vital</em> to successfully using pointers.  However, in production code, it's common to get into much more complex scenarios than these simple demonstrations can encapsulate.</p>\n\n<p>I've been involved with systems where we had structures pointing to other structures pointing to other structures.  Some of those structures also contained embedded structures (rather than pointers to additional structures).  This is where pointers get really confusing.  If you've got multiple levels of indirection, and you start ending up with code like this:</p>\n\n<pre><code>widget-&gt;wazzle.fizzle = fazzle.foozle-&gt;wazzle;\n</code></pre>\n\n<p>it can get confusing really quickly (imagine a lot more lines, and potentially more levels).  Throw in arrays of pointers, and node to node pointers (trees, linked lists) and it gets worse still.  I've seen some really good developers get lost once they started working on such systems, even developers who understood the basics really well.</p>\n\n<p>Complex structures of pointers don't necessarily indicate poor coding, either (though they can).  Composition is a vital piece of good object-oriented programming, and in languages with raw pointers, it will inevitably lead to multi-layered indirection.  Further, systems often need to use third-party libraries with structures which don't match each other in style or technique.  In situations like that, complexity is naturally going to arise (though certainly, we should fight it as much as possible).</p>\n\n<p>I think the best thing colleges can do to help students learn pointers is to to use good demonstrations, combined with projects that require pointer use.  One difficult project will do more for pointer understanding than a thousand demonstrations.  Demonstrations can get you a shallow understanding, but to deeply grasp pointers, you have to really use them.</p>\n"}, {'answer_id': 7283, 'author': 'bruceatk', 'author_id': 791, 'author_profile': 'https://Stackoverflow.com/users/791', 'pm_score': 2, 'selected': False, 'text': "<p>I don't think that pointers themselves are confusing.  Most people can understand the concept.  Now how many pointers can you think about or how many levels of indirection are you comfortable with.  It doesn't take too many to put people over the edge.  The fact that they can be changed accidently by bugs in your program can also make them very difficult to debug when things go wrong in your code.</p>\n"}, {'answer_id': 7510, 'author': 'T Percival', 'author_id': 954, 'author_profile': 'https://Stackoverflow.com/users/954', 'pm_score': 4, 'selected': False, 'text': '<p>I found Ted Jensen\'s &quot;Tutorial on Pointers and Arrays in C&quot; an excellent resource for learning about pointers. It is divided into 10 lessons, beginning with an explanation of what pointers are (and what they\'re for) and finishing with function pointers. <a href="http://web.archive.org/web/20181011221220/http://home.netcom.com:80/%7Etjensen/ptr/cpoint.htm" rel="nofollow noreferrer">http://web.archive.org/web/20181011221220/http://home.netcom.com:80/~tjensen/ptr/cpoint.htm</a></p>\n<p>Moving on from there, Beej\'s Guide to Network Programming teaches the Unix sockets API, from which you can begin to do really fun things. <a href="http://beej.us/guide/bgnet/" rel="nofollow noreferrer">http://beej.us/guide/bgnet/</a></p>\n'}, {'answer_id': 12978, 'author': 'Christopher Scott', 'author_id': 1346, 'author_profile': 'https://Stackoverflow.com/users/1346', 'pm_score': 2, 'selected': False, 'text': "<p>I like the house address analogy, but I've always thought of the address being to the mailbox itself. This way you can visualize the concept of dereferencing the pointer (opening the mailbox). </p>\n\n<p>For instance following a linked list:\n1) start with your paper with the address\n2) Go to the address on the paper\n3) Open the mailbox to find a new piece of paper with the next address on it</p>\n\n<p>In a linear linked list, the last mailbox has nothing in it (end of the list). In a circular linked list, the last mailbox has the address of the first mailbox in it.</p>\n\n<p>Note that step 3 is where the dereference occurs and where you'll crash or go wrong when the address is invalid. Assuming you could walk up to the mailbox of an invalid address, imagine that there's a black hole or something in there that turns the world inside out :)</p>\n"}, {'answer_id': 13096, 'author': 'Wilka', 'author_id': 1367, 'author_profile': 'https://Stackoverflow.com/users/1367', 'pm_score': 7, 'selected': False, 'text': "<p>An analogy I've found helpful for explaining pointers is hyperlinks. Most people can understand that a link on a web page 'points' to another page on the internet, and if you can copy &amp; paste that hyperlink then they will both point to the same original web page. If you go and edit that original page, then follow either of those links (pointers) you'll get that new updated page.</p>\n"}, {'answer_id': 23118, 'author': 'SarekOfVulcan', 'author_id': 2531, 'author_profile': 'https://Stackoverflow.com/users/2531', 'pm_score': 0, 'selected': False, 'text': '<p>Just to confuse things a bit more, sometimes you have to work with handles instead of pointers. Handles are pointers to pointers, so that the back end can move things in memory to defragment the heap. If the pointer changes in mid-routine, the results are unpredictable, so you first have to lock the handle to make sure nothing goes anywhere.</p>\n\n<p><a href="http://arjay.bc.ca/Modula-2/Text/Ch15/Ch15.8.html#15.8.5" rel="nofollow noreferrer">http://arjay.bc.ca/Modula-2/Text/Ch15/Ch15.8.html#15.8.5</a> talks about it a bit more coherently than me. :-)</p>\n'}, {'answer_id': 23241, 'author': 'Baltimark', 'author_id': 1179, 'author_profile': 'https://Stackoverflow.com/users/1179', 'pm_score': 3, 'selected': False, 'text': '<p>I think that what makes pointers tricky to learn is that until pointers you\'re comfortable with the idea that "at this memory location is a set of bits that represent an int, a double, a character, whatever". </p>\n\n<p>When you first see a pointer, you don\'t really get what\'s at that memory location. "What do you mean, it holds an <em>address</em>?"</p>\n\n<p>I don\'t agree with the notion that "you either get them or you don\'t". </p>\n\n<p>They become easier to understand when you start finding real uses for them (like not passing large structures into functions). </p>\n'}, {'answer_id': 35003, 'author': 'joel.neely', 'author_id': 3525, 'author_profile': 'https://Stackoverflow.com/users/3525', 'pm_score': 1, 'selected': False, 'text': "<p>Post office box number.</p>\n\n<p>It's a piece of information that allows you to access something else.</p>\n\n<p>(And if you do arithmetic on post office box numbers, you may have a problem, because the letter goes in the wrong box. And if somebody moves to another state -- with no forwarding address -- then you have a dangling pointer. On the other hand -- if the post office forwards the mail, then you have a pointer to a pointer.)</p>\n"}, {'answer_id': 758499, 'author': 'Breton', 'author_id': 51101, 'author_profile': 'https://Stackoverflow.com/users/51101', 'pm_score': 3, 'selected': False, 'text': '<p>The problem with pointers is not the concept. It\'s the execution and language involved. Additional confusion results when teachers assume that it\'s the CONCEPT of pointers that\'s difficult, and not the jargon, or the convoluted mess C and C++ makes of the concept. So vast amounts of effort are poored into explaining the concept (like in the accepted answer for this question) and it\'s pretty much just wasted on someone like me, because I already understand all of that. It\'s just explaining the wrong part of the problem.</p>\n\n<p>To give you an idea of where I\'m coming from, I\'m someone who understands pointers perfectly well, and I can use them competently in assembler language. Because in assembler language they are not referred to as pointers. They are referred to as addresses. When it comes to programming and using pointers in C, I make a lot of mistakes and get really confused. I still have not sorted this out. Let me give you an example.</p>\n\n<p>When an api says:</p>\n\n<pre><code>int doIt(char *buffer )\n//*buffer is a pointer to the buffer\n</code></pre>\n\n<p>what does it want?</p>\n\n<p>it could want:</p>\n\n<p>a number representing an address to a buffer</p>\n\n<p>(To give it that, do I say <code>doIt(mybuffer)</code>, or <code>doIt(*myBuffer)</code>?)</p>\n\n<p>a number representing the address to an address to a buffer</p>\n\n<p>(is that <code>doIt(&amp;mybuffer)</code> or <code>doIt(mybuffer)</code> or <code>doIt(*mybuffer)</code>?)</p>\n\n<p>a number representing the address to the address to the address to the buffer</p>\n\n<p>(maybe that\'s <code>doIt(&amp;mybuffer)</code>. or is it <code>doIt(&amp;&amp;mybuffer)</code> ? or even <code>doIt(&amp;&amp;&amp;mybuffer)</code>)</p>\n\n<p>and so on, and the language involved doesn\'t make it as clear because it involves the words "pointer" and "reference" that don\'t hold as much meaning and clarity to me as "x holds the address to y" and "this function requires an address to y". The answer additionally depends on just what the heck "mybuffer" is to begin with, and what doIt intends to do with it. The language doesn\'t support the levels of nesting that are encountered in practice. Like when I have to hand a "pointer" in to a function that creates a new buffer, and it modifies the pointer to point at the new location of the buffer. Does it really want the pointer, or a pointer to the pointer, so it knows where to go to modify the contents of the pointer. Most of the time I just have to guess what is meant by "pointer" and most of the time I\'m wrong, regardless of how much experience I get at guessing.</p>\n\n<p>"Pointer" is just too overloaded. Is a pointer an address to a value? or is it a variable that holds an address to a value. When a function wants a pointer, does it want the address that the pointer variable holds, or does it want the address to the pointer variable?\nI\'m confused.</p>\n'}, {'answer_id': 758569, 'author': 'Waylon Flinn', 'author_id': 74291, 'author_profile': 'https://Stackoverflow.com/users/74291', 'pm_score': 2, 'selected': False, 'text': '<p>I think it might actually be a syntax issue. The C/C++ syntax for pointers seems inconsistent and more complex than it needs to be.</p>\n\n<p>Ironically, the thing that actually helped me to understand pointers was encountering the concept of an iterator in the c++ <a href="http://www.sgi.com/tech/stl/stl_introduction.html" rel="nofollow noreferrer">Standard Template Library</a>. It\'s ironic because I can only assume that iterators were conceived as a generalization of the pointer.</p>\n\n<p>Sometimes you just can\'t see the forest until you learn to ignore the trees.</p>\n'}, {'answer_id': 758598, 'author': 'rama-jka toti', 'author_id': 75248, 'author_profile': 'https://Stackoverflow.com/users/75248', 'pm_score': 1, 'selected': False, 'text': '<p>Not a bad way to grasp it, via iterators.. but keep looking you\'ll see Alexandrescu start complaining about them.</p>\n\n<p>Many ex-C++ devs (that never understood that iterators are a modern pointer before dumping the language) jump to C# and still believe they have decent iterators.</p>\n\n<p>Hmm, the problem is that all that iterators are is in complete odds at what the runtime platforms (Java/CLR) are trying to achieve: new, simple, everyone-is-a-dev usage. Which can be good, but they said it once in the purple book and they said it even before and before C:</p>\n\n<p>Indirection.</p>\n\n<p>A very powerful concept but never so if you do it all the way.. Iterators are useful as they help with abstraction of algorithms, another example. And compile-time is the place for an algorithm, very simple. You know code + data, or in that other language C#:</p>\n\n<p>IEnumerable + LINQ + Massive Framework = 300MB runtime penalty indirection of lousy, dragging apps via heaps of instances of reference types..</p>\n\n<p>"Le Pointer is cheap."</p>\n'}, {'answer_id': 761227, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>The reason it's so hard to understand is not because it's a difficult concept but because <strong>the syntax is inconsistent</strong>.</p>\n<pre><code>int *mypointer;\n</code></pre>\n<p>You are first learned that the leftmost part of a variable creation defines the type of the variable. Pointer declaration does not work like this in C and C++. Instead they say that the variable is pointing on the type to the left. In this case: <em><code>*</code>mypointer <strong>is pointing</strong> on an int.</em></p>\n<p>I didn't fully grasp pointers until i tried using them in C# (with unsafe), they work in exact same way but with logical and consistent syntax. The pointer is a type itself. Here <em>mypointer <strong>is</strong> a pointer to an int.</em></p>\n<pre><code>int* mypointer;\n</code></pre>\n<p>Don't even get me started on function pointers...</p>\n"}, {'answer_id': 800619, 'author': 'toto', 'author_id': 92942, 'author_profile': 'https://Stackoverflow.com/users/92942', 'pm_score': 3, 'selected': False, 'text': "<p>I could work with pointers when I only knew C++. I kind of knew what to do in some cases and what not to do from trial/error. But the thing that gave me complete understanding is assembly language. If you do some serious instruction level debugging with an assembly language program you've written, you should be able to understand a lot of things.</p>\n"}, {'answer_id': 819331, 'author': 'Joshua Fox', 'author_id': 39242, 'author_profile': 'https://Stackoverflow.com/users/39242', 'pm_score': 2, 'selected': False, 'text': '<p>The confusion comes from the multiple abstraction layers mixed together in the "pointer" concept. Programmers don\'t get confused by ordinary references in Java/Python, but pointers are different in that they expose characteristics of the underlying memory-architecture.</p>\n\n<p>It is a good principle to cleanly separate layers of abstraction, and pointers do not do that.</p>\n'}, {'answer_id': 2057116, 'author': 'Ryan Lundy', 'author_id': 5486, 'author_profile': 'https://Stackoverflow.com/users/5486', 'pm_score': 5, 'selected': False, 'text': '<p>The reason I had a hard time understanding pointers, at first, is that many explanations include a lot of crap about passing by reference.  All this does is confuse the issue.  When you use a pointer parameter, you\'re <em>still</em> passing by value; but the value happens to be an address rather than, say, an int.</p>\n\n<p>Someone else has already linked to this tutorial, but I can highlight the moment when I began to understand pointers:</p>\n\n<p><a href="http://pweb.netcom.com/~tjensen/ptr/ch3x.htm" rel="noreferrer">A Tutorial on Pointers and Arrays in C: Chapter 3 - Pointers and Strings</a></p>\n\n<pre><code>int puts(const char *s);\n</code></pre>\n\n<blockquote>\n  <p>For the moment, ignore the <code>const.</code> The parameter passed to <code>puts()</code> is a pointer, <strong>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.</strong> Thus when we write <code>puts(strA);</code> as we have seen, we are passing the address of strA[0].</p>\n</blockquote>\n\n<p>The moment I read these words, the clouds parted and a beam of sunlight enveloped me with pointer understanding.</p>\n\n<p>Even if you\'re a VB .NET or C# developer (as I am) and never use unsafe code, it\'s still worth understanding how pointers work, or you won\'t understand how object references work.  Then you\'ll have the common-but-mistaken notion that passing an object reference to a method copies the object.</p>\n'}, {'answer_id': 2057337, 'author': 'jalf', 'author_id': 33213, 'author_profile': 'https://Stackoverflow.com/users/33213', 'pm_score': 3, 'selected': False, 'text': '<p>I think the main barrier to understanding pointers is bad teachers.</p>\n\n<p>Almost everyone are taught lies about pointers: That they are <em>nothing more than memory addresses</em>, or that they allow you to point to <em>arbitrary locations</em>. </p>\n\n<p>And of course that they are difficult to understand, dangerous and semi-magical.</p>\n\n<p>None of which is true. Pointers are actually fairly simple concepts, <em>as long as you stick to what the C++ language has to say about them</em> and don\'t imbue them with attributes that "usually" turn out to work in practice, but nevertheless aren\'t guaranteed by the language, and so aren\'t part of the actual concept of a pointer.</p>\n\n<p>I tried to write up an explanation of this a few months ago in <a href="https://github.com/kgisl/cs8251/blob/master/files/pointerConspiracy2.pdf" rel="nofollow noreferrer">this blog post</a> -- hopefully it\'ll help someone.</p>\n\n<p>(Note, before anyone gets pedantic on me, yes, the C++ standard does say that pointers <em>represent</em> memory addresses. But it does not say that "pointers are memory addresses, and nothing but memory addresses and may be used or thought of interchangeably with memory addresses". The distinction is important)</p>\n'}, {'answer_id': 13204366, 'author': 'nurmurat', 'author_id': 887620, 'author_profile': 'https://Stackoverflow.com/users/887620', 'pm_score': 0, 'selected': False, 'text': '<p>Every C/C++ beginner has the same problem and that problem occurs not because "pointers are hard to learn" but "who and how it is explained". Some learners gather it verbally some visually and the best way of explaining it is to use <strong>"train" example</strong> (suits for verbal and visual example).</p>\n\n<p>Where <strong>"locomotive"</strong> is a pointer which <strong>can not</strong> hold anything and <strong>"wagon"</strong> is  what "locomotive" tries pull (or point to). After, you can classify the "wagon" itself, can it hold animals,plants or people (or a mix of them).</p>\n'}, {'answer_id': 15842434, 'author': 'Mike', 'author_id': 1348709, 'author_profile': 'https://Stackoverflow.com/users/1348709', 'pm_score': 3, 'selected': False, 'text': '<p>I thought I\'d add an analogy to this list that I found very helpful when explaining pointers (back in the day) as a Computer Science Tutor; first, let\'s:</p>\n\n<hr>\n\n<p><strong>Set the stage</strong>: </p>\n\n<p>Consider a parking lot with 3 spaces, these spaces are numbered:</p>\n\n<pre><code>-------------------\n|     |     |     |\n|  1  |  2  |  3  |\n|     |     |     |\n</code></pre>\n\n<p>In a way, this is like memory locations, they are sequential and contiguous.. sort of like an array. Right now there are no cars in them so it\'s like an empty array (<code>parking_lot[3] = {0}</code>).</p>\n\n<hr>\n\n<p><strong>Add the data</strong></p>\n\n<p>A parking lot never stays empty for long... if it did it would be pointless and no one would build any. So let\'s say as the day moves on the lot fills up with 3 cars, a blue car, a red car, and a green car:</p>\n\n<pre><code>   1     2     3\n-------------------\n| o=o | o=o | o=o |\n| |B| | |R| | |G| |\n| o-o | o-o | o-o |\n</code></pre>\n\n<p>These cars are all the same type (car) so one way to think of this is that our cars are some sort of data (say an <code>int</code>) but they have different values (<code>blue</code>, <code>red</code>, <code>green</code>; that could be an color <code>enum</code>)</p>\n\n<hr>\n\n<p><strong>Enter the pointer</strong></p>\n\n<p>Now if I take you into this parking lot, and ask you to find me a blue car, you extend one finger and use it to point to a blue car in spot 1. This is like taking a pointer and assigning it to a memory address (<code>int *finger = parking_lot</code>)</p>\n\n<p>Your finger (the pointer) is not the answer to my question. Looking <strong><em>at</em></strong> your finger tells me nothing, but if I look where you\'re finger is <em>pointing to</em> (dereferencing the pointer), I can find the car (the data) I was looking for.</p>\n\n<hr>\n\n<p><strong>Reassigning the pointer</strong></p>\n\n<p>Now I can ask you to find a red car instead and you can redirect your finger to a new car. Now your pointer (the same one as before) is showing me new data (the parking spot where the red car can be found) of the same type (the car). </p>\n\n<p>The pointer hasn\'t physically changed, it\'s still <em>your</em> finger, just the data it was showing me changed. (the "parking spot" address)</p>\n\n<hr>\n\n<p><strong>Double pointers (or a pointer to a pointer)</strong></p>\n\n<p>This works with more than one pointer as well. I can ask where is the pointer, which is pointing to the red car and you can use your other hand and point with a finger to the first finger. (this is like <code>int **finger_two = &amp;finger</code>)</p>\n\n<p>Now if I want to know where the blue car is I can follow the first finger\'s direction to the second finger, to the car (the data). </p>\n\n<hr>\n\n<p><strong>The dangling pointer</strong></p>\n\n<p>Now let\'s say you\'re feeling very much like a statue, and you want to hold your hand pointing at the red car indefinitely. What if that red car drives away?</p>\n\n<pre><code>   1     2     3\n-------------------\n| o=o |     | o=o |\n| |B| |     | |G| |\n| o-o |     | o-o |\n</code></pre>\n\n<p>Your pointer is still pointing to where the red car <em>was</em> but is no longer. Let\'s say a new car pulls in there... a Orange car. Now if I ask you again, "where is the red car", you\'re still pointing there, but now you\'re wrong. That\'s not an red car, that\'s orange. </p>\n\n<hr>\n\n<p><strong>Pointer arithmetic</strong></p>\n\n<p>Ok, so you\'re still pointing at the second parking spot (now occupied by the Orange car)</p>\n\n<pre><code>   1     2     3\n-------------------\n| o=o | o=o | o=o |\n| |B| | |O| | |G| |\n| o-o | o-o | o-o |\n</code></pre>\n\n<p>Well I have a new question now... I want to know the color of the car in the <em>next</em> parking spot. You can see you\'re pointing at spot 2, so you just add 1 and you\'re pointing at the next spot.  (<code>finger+1</code>), now since I wanted to know what the data was there, you have to check that spot (not just the finger) so you can deference the pointer (<code>*(finger+1)</code>) to see there is a green car present there (the data at that location)</p>\n'}, {'answer_id': 16264783, 'author': 'Bernd Jendrissek', 'author_id': 117911, 'author_profile': 'https://Stackoverflow.com/users/117911', 'pm_score': 1, 'selected': False, 'text': '<p>Some answers above have asserted that "pointers aren\'t really hard", but haven\'t gone on to address directly where "pointer are hard!" comes from. Some years back I tutored first year CS students (for only one year, since I clearly sucked at it) and it was clear to me that the <strong>idea</strong> of pointer is not hard. What\'s hard is understanding <strong>why and when you would want a pointer</strong>.</p>\n\n<p>I don\'t think you can divorce that question - why and when to use a pointer - from explaining broader software engineering issues. Why every variable should <em>not</em> be a global variable, and why one should factor out similar code into functions (that, get this, use <em>pointers</em> to specialize their behaviour to their call site).</p>\n'}, {'answer_id': 16694780, 'author': 'sashoalm', 'author_id': 492336, 'author_profile': 'https://Stackoverflow.com/users/492336', 'pm_score': 2, 'selected': False, 'text': '<p>The way I liked to explain it was in terms of arrays and indexes - people might not be familiar with pointers, but they generally know what an index is.</p>\n\n<p>So I say imagine that the RAM is an array (and you have only 10-bytes of RAM):</p>\n\n<pre><code>unsigned char RAM[10] = { 10, 14, 4, 3, 2, 1, 20, 19, 50, 9 };\n</code></pre>\n\n<p>Then a pointer to a variable is really just the index of (the first byte of) that variable in the RAM.</p>\n\n<p>So if you have a pointer/index <code>unsigned char index = 2</code>, then the value is obviously the third element, or the number 4. A pointer to a pointer is where you take that number and use it as an index itself, like <code>RAM[RAM[index]]</code>.</p>\n\n<p>I would draw an array on a list of paper, and just use it to show things like many pointers pointing to the same memory, pointer arithmetic, pointer to pointer, and so on.</p>\n'}]
['https://Stackoverflow.com/questions/5727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/568/']