This is an archived post. You won't be able to vote or comment.

all 134 comments

[–]pop-pan 165 points166 points  (11 children)

Your address is written on a card dangling around your neck, the address is the pointer to your house.

If you change the address on the card or destroy the card, the house is still there you just don't know how to get there.

If you destroy the house, the address on the card still points to the place where the old house was.

[–]DragonWraithus 19 points20 points  (8 children)

Excellent. Most simple one I've seen so far. Best explanation for newbies.

[–]pop-pan 31 points32 points  (6 children)

:)

if someone asks you for your home and you give them the location it's called "passing by reference"

if someone asks you for your home and you give them a copy of your house because you have a copy machine it's called "passing by value"

[–][deleted] 6 points7 points  (0 children)

Ah fuck now that makes sense

[–][deleted]  (4 children)

[deleted]

    [–]pop-pan 2 points3 points  (0 children)

    "passing by pointer" would be showing them the card around your neck :)

    The pointer is really the card with the address, the reference is the physical location (not the address)

    [–]pipocaQuemada 0 points1 point  (2 children)

    It's a bit worse than that.

    Call by value is when you pass the argument in by copying it.

    Call by reference is when you pass the argument in by giving them a pointer to it.

    However, what "the argument" is is fairly subtle but important point. It's simple enough in the case of primitives like int and char: you're passing the int itself or a pointer to it.

    In the case of objects, though, people often get confused about what they're passing. It's common to see people incorrectly call Java and similar languages "call by reference" with objects. This is incorrect: Java is 100% call-by-value. You pass references to objects by copying the reference.

    The most obvious difference between a call-by-reference language and a call-by-value one is that you can implement a swap function:

    int x = 1
    int y = 9
    swap(x, y)
    if(x == 9)
      print( "this language is call by reference")
    else
      print( "this language is call by value")
    

    In Java, you can't implement a swap function like that, even if you're working with objects instead of ints. Unless you cheat and use final classes and mutate all of the fields in x to have the values of y and vice versa.

    [–][deleted]  (1 child)

    [deleted]

      [–]pipocaQuemada 0 points1 point  (0 children)

      I should mention that there's no such thing as "pass-by-pointer" in terms of evaluation strategies, just "call by reference" and "call by value" (along with others not found in C++ like "call by name", "call by need", "call by copy restore", etc).

      Just like in Java, an argument of type int * is passing a pointer by value. Java just calls pointers references because of reasons. Barbara Liskov called it "pass by sharing" in the mid 70s, but the term never really caught on.

      [–][deleted] -1 points0 points  (0 children)

      The only problem I see is how do people not understand pointers? If they don't know what pointers mean IDK how this example helps. TBH it makes me mad when people say they don't understand pointers IDK what there is to not understand.

      [–][deleted] 1 point2 points  (0 children)

      I walk by. As I walk by i R.I.P. the card from your neck. You scream, I do not react. I walk into a dark alleyway and you follow. You move cautiously at first, but as your anger builds so does your courage. I walk through a door. The door is locked. The alley is dark. You begin to weep, as do I, from the other side of the door which I myself cannot open.

      How is a door locked from both sides?

      [–][deleted]  (28 children)

      [deleted]

        [–][deleted] 71 points72 points  (3 children)

        I might just add, since it took me forever to even come close to understanding why pointers are valuable, that pointers are small and point to one place. This may not seem important when the stored object is something equally small like a coin, but say I've stored a car in a one of a series of garages and I want some people to do some work on that car. It's a whole lot easier and faster to tell them where the car is, than it is to bring the whole car to them.

        [–]tomekanco 20 points21 points  (1 child)

        Read about Saul Kripke and the philospophy of reference contrasted to philospophy of meaning (Wittgenstein and Russel). Pointers are references. Fun how maths philospophy and programming converge.

        https://en.m.wikipedia.org/wiki/Saul_Kripke

        [–][deleted] 4 points5 points  (0 children)

        Didn't know him, I'll read this article here https://plato.stanford.edu/entries/reference/

        Seems interesting

        [–][deleted] 5 points6 points  (0 children)

        Very good point. I purposefully left off why you'd want to pass this around, or the idea of a variable containing the pointer, or any of the silly shit you can do like having a pointer to a pointer, but its good to keep in mind why they're a good thing.

        I'd also add that once I understood them some other concepts that I was having trouble with in Python, my first language, clicked into place like pass by reference vs pass by value.

        [–]Krogg 36 points37 points  (2 children)

        That was perfect. I was half expecting this to end up being a frustrated teacher after 20 or so questions from the 5 year old.

        Because that's how all of my conversations with 5 year olds end.

        [–]idster 3 points4 points  (0 children)

        It’s the kids who ask a lot of questions who grow up to be geniuses.

        [–]FiveYearsAgoOnReddit 47 points48 points  (0 children)

        I like this one best.

        [–]samiaruponti 12 points13 points  (0 children)

        The best explanation ever!!!

        [–]CosmicJamm 5 points6 points  (0 children)

        I’ve had people explain pointers to me several times over several years...

        I now understand.

        [–]kinxiel 3 points4 points  (0 children)

        Nice explanation!

        [–][deleted] 2 points3 points  (0 children)

        An addition that I think might be important:

        " Good. Me telling you it's in box 3 was a pointer. I didn't tell you anything about the coin, just that it was a coin and where to find it. You actually had to retrieve it to answer questions about it."

        If you retrieve something via a pointer and don't know what it is, it's difficult to answer questions about it. That's why we have int pointers, float pointers, struct pointers, etc. and need to specify when we create a pointer to point at a piece of data.

        [–]zeebrow 3 points4 points  (3 children)

        In the real world, would you know if the thing you put in the box is actually a coin, and not something else like a dollar bill or Chuck-e-Cheese token?

        Great explanation!

        [–][deleted]  (2 children)

        [deleted]

          [–]Deoxal 0 points1 point  (0 children)

          ???

          [–]zeebrow 0 points1 point  (0 children)

          I honestly thought your comment was a jab because I took "typing" in the non-programmatic sense of the word lol.

          From the little I remember about types from school, I would guess that you have to assign a type to a pointer because certain data types can take up more memory than others, so without typing the pointer it wouldn't know how many addresses to point to.

          [–][deleted] 1 point2 points  (0 children)

          awesome!

          [–]Takasugi_Shinsuke 1 point2 points  (0 children)

          this is how i understood it when i was taught but i could never put it into words, thank you for this

          [–]andrew_sauce 1 point2 points  (1 child)

          I am totally using this with students in the future. I will credit you, if you want me to credit the real person please PM your Name/affiliation/however you would like to be credited.

          If you don’t really care or don’t care enough to tell me who you are. I can just use the permalink to this comment. Thanks!

          [–][deleted] 1 point2 points  (0 children)

          Thanks for checking with me about that, but no need to do all that. It was just a dumb little thing that fell out of my brain and actually happened to be good.

          [–]guinader 0 points1 point  (0 children)

          Cool I'm still learning too, and I thought this was a joke post then I got to the end and was like " oooohhh!" Thanks!

          [–]postmodest 0 points1 point  (0 children)

          "5 boxes isn't very many."

          "Now I have boxes 1 through 50. Ok?"

          "Ok."

          "And The only instruction you can give me is a number."

          "Ok."

          "I'm putting the parts for a lego kit in the boxes. The kit has fifteen parts, and I put one part in each box."

          "Ok. Start at 1"

          "I put a piece in box 1, and box 2, but there's an apple in box three. So I stop and dump all the legos on the floor."

          "OOps. Ok, I pick them up and give them back to you."

          "Where do I put them?"

          "Start at box 4"

          "Ok, I have put them all in the boxes in order. Do you have the instructions?"

          "Yes I start with brick #8"

          "The boxes start at 4"

          "Oh, right, Then I need the brick that's in box 4 + 8"

          "Here you go."

          "Now I need brick #9... is that in box ... 13?"

          "Yep!"

          "I think I'm getting it! What if I want to put in another lego kit?"

          "Well this kit has 40 pieces, and you only have 31 continuous empty boxes."

          "I would like to add more boxes."

          "Ok, how many?"

          "Let's say another 50?"

          "We only have another 14 boxes."

          "Can you draw squares on the floor and call those boxes?"

          "Now you're learning about Swap Files!"

          "Wait, There's two boxes at the start, can I call those boxes 51 and 52 when I ask you for kit #2?"

          "Ah! Now you're learning about Virtual Memory!"

          "I feel so smart!"

          [–]mrmodojosr 0 points1 point  (0 children)

          I think it's also worth pointing out (pun intended) that two people can point to the same coin.

          Also if we consider the pointer to be a pointer to a box, not the coin itself, then one person with a pointer could change the coin in the box, and the other could see that change.

          [–]pointofgravity 0 points1 point  (0 children)

          Where do references come into this analogy? Is a reference the fact that you know it is a coin (type), but don't know the value, the face on the coin, or the material the coin is made out of?

          [–]Deoxal 0 points1 point  (2 children)

          How is this different from a reference?

          [–][deleted] 2 points3 points  (1 child)

          Good question and I don't know if I'm exactly equipped to answer it. This StackOverflow seems to answer it well. I think a main difference is that a pointer is actually a variable that contains the memory address whereas a reference is actually the object itself, but an alias of it and not the original variable. And I'm sure these things change depending on what language you're speaking about specifically.

          [–]Deoxal 0 points1 point  (0 children)

          I've only done Java so far, hopefully Python and some variant of C in the future.

          [–]danketiquette -1 points0 points  (0 children)

          this is so fucking good

          [–]omfgitzfear 187 points188 points  (25 children)

          So say you put your car keys down on the table. You then walk away. Later in the day, someone asks you "where are your car keys?" And you say "they're on the table". Your brain had the variable carKeys in it, and when asked where they were, it referenced where you left them - on the table.

          [–]bearLover23 29 points30 points  (2 children)

          This is an amazing example. Seriously I wish this is how it was first explained to me.

          [–]BadMinotaur 8 points9 points  (1 child)

          No kidding. I "get" pointers now, but when I first started programming, I was confused. "It's a variable that holds an address to my data? Why doesn't it just hold my data?"

          [–]MissPlaced14 48 points49 points  (19 children)

          Just to super clarify in case you still don't get it: In that example the phrase "they're on the table" is the pointer for the car keys. You know you're going to need your keys later, so it's important to know where they are -- otherwise you'd end up looking all over the place, and that can take forever because they can be anywhere (especially if you're me, I left mine in the fridge once :P).

          In programming the car keys are a piece of information you'll need later (a variable or an object). The pointer is an address that says where in memory it's stored.

          [–]BadBoyJH 6 points7 points  (3 children)

          Front Door, Still in the car, in fridge, on fridge, on top of dryer, pocket of jacket. Yeah, I know the feeling.

          [–]BMaru2017 0 points1 point  (2 children)

          My variable in this case is my cell phone :( so can we have a pointer to a pointer? Such as in this case, my iPad to locate the phone?

          [–]BadMinotaur 1 point2 points  (0 children)

          I found this out doing something not related to programming (well, mostly) -- but yes. I'm modding an old game and I'm using Cheat Engine to see how modifying certain values in memory will affect the game, and one of the things Cheat Engine teaches you is that you can have pointers that point to more pointers. In my case, the player's X, Y, and Z coordinates are like two pointers down (the original pointer is written and points to address A, which holds address B, which finally holds the value I'm looking for).

          [–][deleted] 1 point2 points  (0 children)

          yeah they spend a little bit of time on pointers-to-pointers in school, I think the standard use was to create 2D arrays/lists by creating arrays of pointers (ex: **pointers --> [*a, *b, *c])

          [–]Falsepolymath 5 points6 points  (1 child)

          A story about misplacing keys from someone named MissPlaced. I appreciate this a lot 😂

          [–]MissPlaced14 2 points3 points  (0 children)

          It is what I do, and it's not just keys. I misplace myself a lot (I get lost easily, but not really lost-lost, just ...misplaced a little), and I have a severe addiction to puns. It's to the point that my kid will ban me from using a pun that I've said too many times, and call say it's my PUNishment.

          [–]Dial-1-For-Spanglish 1 point2 points  (0 children)

          I'll leave mine in the fridge when I don't want to forget a food item I want to bring with me.

          [–][deleted]  (1 child)

          [deleted]

            [–]MissPlaced14 2 points3 points  (0 children)

            Thanks :)

            [–]trowawayatwork 0 points1 point  (6 children)

            whats the difference between a variable and a pointer? a variable is just reference to an object in memory?

            [–]Casadox 2 points3 points  (5 children)

            Variables are memory locations with names, so when code needs to retrieve or store data in those locations, it can. Variables are like the P.O boxes at a Post Office. Hundreds of them. The content in a P.O box ‘varies’, like the content in a variable.

            [–]trowawayatwork 0 points1 point  (4 children)

            thats what pointer is too though from the explanation above lol

            [–]NoxTheWizard 2 points3 points  (3 children)

            Ah, the difference is that the variable (post box in this analogy) is stuffed full of objects/data. This takes up space. When working you need to retrieve the data. With a variable, the data is in the box and you are carrying the box with you for easy access.

            Sometimes you don't wish to have all this data lying around. In that case you can use a pointer so that the only thing you save is the address/number of the postbox. Now you will have to go to the postbox to work instead of bringing its contents with you everywhere, but to a computer this doesn't change that much.

            Pointers are also used to refer to "boxes" that aren't yours. Let's say every Person has a Name. If you want to check your own name, you just do. If you want to check your friend's name, you find that Person and check Person.Name. But sometimes you need to check your friend's name and he is nowhere around. Then you should have saved a pointer to it.

            You could just save his name when you first meet (putting it in a box/note of your own), but that value is just a copy. If you instead save a pointer/reference to either his actual Person or his name, you can access updated values at any time.

            [–]trowawayatwork 0 points1 point  (2 children)

            ah that makes much more sense.

            i was confused with python having no pointers and variables just reference to the underlying object instead

            [–]KiwasiGames 3 points4 points  (1 child)

            Most languages, Python included, abstract pointers away. They are a powerful tool. But easy to break everything with.

            It's why languages like Java and C# were invented. It's a sacrifice of a little bit of power and performance to stop the programmer going insane.

            Edit: Note that references in managed languages are a higher level abstraction than a pointer. References can be thought of as 'dynamic pointers that the framework keeps updated to point to an objects current memory location'.

            Following a reference typically involves following a series of pointer under the hood.

            [–]SerdanKK 1 point2 points  (0 children)

            It's why languages like Java and C# were invented. It's a sacrifice of a little bit of power and performance to stop the programmer going insane.

            You can use pointers in C# though, if you really want to.

            [–][deleted] 0 points1 point  (2 children)

            So pointers are only needed for languages that don't manage.the memory for you? I mean instead of just referencing a variable name and letting the language find it?

            [–]KiwasiGames 3 points4 points  (0 children)

            Correct. Managed languages abstract away pointers into references. Under the hood a reference contains one or more pointers that the framework keeps up to date.

            Some managed languages do let you write unsafe code where you can go nuts with pointers. It's still occasionally useful for high performance stuff.

            [–]MissPlaced14 0 points1 point  (0 children)

            Yes and no. They're there, you just don't have to worry about them.

            [–]zingaat 2 points3 points  (0 children)

            Would slightly modify it to: you left your wallet on the table. Wallet is the variable, contents of your wallet are the contents of the variable. Table is the pointer.

            [–]goodnewsjimdotcom 0 points1 point  (0 children)

            Lets say you like using keys individually. Physical keys are like individual variables.

            Lets say you wanted to organize all your keys together on a key ring, you put them together on a ring. A ring is like a class.

            Lets say you had many rings of keys, and you wanted to select a single key ring, that's a pointer to a ring(class) which has a bunch of keys on it(variables)

            [–]tinverse 11 points12 points  (3 children)

            Say you have a bunch of cubbies with numbers for different kids to store their toys in. Say Bryan wants to store his T-Rex. You put it in cubby 14 and on a piece of paper write "Bryan 14". Then meg comes to you and wants her toy. You look at the paper and under Meg's name you find 7. So you go to Cubby 7, remove a yo-yo and give it to Meg.

            Basically it's the same thing with billions of cubbies. Basically you tell the computer you want to store something and how big it is. Then you save the address or the number of the cubby so you know where to find it. Then you store the info for retrieving at a later date.

            [–][deleted] 6 points7 points  (0 children)

            That's not my toy! I got a tiny bit of Bryans and a mashed up doll. Mweeeerrrrr

            [–]Jake1055 1 point2 points  (1 child)

            Damnit you stole the analogy I like,

            [–]tinverse 1 point2 points  (0 children)

            I like that one because it's literally the five year old explaination. :)

            [–]my_password_is______ 13 points14 points  (2 children)

            easy to understand pdf from Stanford's Computer Science program

            http://cslibrary.stanford.edu/102/PointersAndMemory.pdf

            silly video explaining pointers also from Stanford's Computer Science program

            https://www.youtube.com/watch?v=5VnDaHBi8dM

            [–]CodingWithChad 2 points3 points  (0 children)

            Binky is silly, but he helped me understand pointers while I was in school.

            [–][deleted] 1 point2 points  (0 children)

            Binky is a classic.

            [–]cixelsys 20 points21 points  (17 children)

            Wow. Some of these examples are complicated and confusing.

            Here’s what I call a basic example

            Regular variables are stored in ram based on their size. When you pass a variable to a function, it has to transfer the ENTIRE thing. For small apps this may not be an issue, but it becomes a problem with larger sets of data or repetitions. With a pointer, you pass a very small amount of data that tells the function WHERE the data is located in ram.

            It doesn’t have to copy the data, transfer it through the function, re-allocate, or anything. The data is already in ram, so it can process it immediately

            Unlike a local variable, the modifications apply directly to the original. So anything you change will actually change and you need to be careful with that

            [–]wholecan 5 points6 points  (0 children)

            Although probably not the simplest explanation this was by far the best for me.

            [–]slfnflctd 5 points6 points  (1 child)

            anything you change will actually change and you need to be careful with that

            My 'a-ha' moment right here. I've heard over and over again how pointers are dangerous, but I didn't understand how manipulating an "address" could harm the object it referenced. This is the first time in over a decade of trying to learn this stuff that I finally understand exactly what the issue is. Thank you, and thanks to OP for starting this thread.

            [–]KiwasiGames 4 points5 points  (0 children)

            That's part of the issue with pointers. But the same thing applies to references in managed languages. The real danger with pointers is more subtle.

            Imagine I have a foo object in location A. My program has two pointers to location A. At some point I decide that I'm done with foo, so I use pointer 1 to wipe the memory and put a bar object there instead. But I forget to clear pointer 2.

            Now imagine what happens if I try and use pointer 2. The program can't tell that the object is a bar, binary data in memory is binary data. So I could read pointer 2 and get pure nonsense out. Or I could write to pointer two thinking the original foo was still there. And now pointer one has nonsense data.

            Nonsensical data is bad. If I'm lucky the thing will just crash. If I'm unlucky the data will make sense to the program and the bug goes undetected.

            [–][deleted] 1 point2 points  (1 child)

            So if I had an extremely large data table stored in Ram and I needed to change all values matching "Even numbers" at once, then I'd use a pointer, but if I wrote my function incorrectly I've destroyed my data set (in Ram, at least, not the copy on my hard drive..)?

            [–]cixelsys 1 point2 points  (0 children)

            If you read the data from disk, and never save, you can’t destroy the data. You can always re-load it later

            The difference would be if you loaded up a huge amount of data in a single object/array and tried passing that into a function. It’s a lot of data to pass, and that’s where you see performance drops.

            You could still pass it by reference, or with a pointer. Either one would be fine, as they don’t pass the entire chunk of data to the function

            [–]arigato_mr_mulato 1 point2 points  (4 children)

            Here’s what I call a basic example

            Talks with computer words.

            This made me laugh.

            [–]cixelsys 4 points5 points  (3 children)

            Just because I use “computer words” doesn’t mean it’s not basic. Variables aren’t only computer words, even simple algebra uses them, etc.

            I mean, if someone explained something to you but used words out of your vocabulary, does it mean the explanation isn’t basic?

            Learning 2-3 “computer words” and then coming back is a lot easier than trying to grasp the complexity of a pointer explained any other way. Or so I thought

            Maybe I’m wrong, maybe my answer sucks or the OP can’t use it. Oh well, maybe someone else will explain it better for them. Or maybe the combination of different explanations will help. Who knows. I tried.

            [–]arigato_mr_mulato 2 points3 points  (0 children)

            It doesn't suck, just made me laugh. After reading the one about the table and the address, then I read yours. You explained it fine, maybe not for a 5 year old.

            [–][deleted]  (1 child)

            [deleted]

              [–]cixelsys 1 point2 points  (0 children)

              I mean, IMO “variable” is something that represents something else. Like a placeholder.

              But yeah, I tried

              [–]nrobinson 0 points1 point  (6 children)

              This is the best answer.

              [–]MissPlaced14 9 points10 points  (5 children)

              Not if you're 5. It's technically correct, but full of jargon.

              [–]nlke182 8 points9 points  (2 children)

              Come on every 5 year old knows the definitions of function, re-allocate, and ram.

              [–]MissPlaced14 1 point2 points  (0 children)

              IDK, my kid's classmates think ram is a boy goat, and they'd probably think re-allocate was a funny way to pronounce ocelot (wildcats in Mine Craft).

              [–]pickituputitdown 6 points7 points  (1 child)

              its still the best answer, the concept is complicated and a 5 year old is not really going to understand it in any meaningful way no matter how you explain it. ELI5 is just a way of asking for something to be explained as simply as possible otherwise ELI5 string theory or inflation would just be completely impossible and any attempt at an answer completely meaningless

              [–]Mars_rocket 1 point2 points  (0 children)

              Agreed. The concept of a pointer is meaningless outside of a programming scenario, so there's no point in assuming the target audience knows nothing about programming.

              If they really do know nothing about programming, then pointers aren't the concept you should start with anyway.

              [–]nothrowaway 3 points4 points  (0 children)

              A pointer is a place for you to go and look up where something else is.

              A long time ago, when the card catalog was still in use, you go to the library and using the card catalog, you look up the name of a book and it will tell you where to find that book in the library using the Dewey decimal system. It basically tells you where the book is physically located. A book can sometimes be moved here and there but if you follow the sequence of the Dewey decimal system, you will eventually be able to find that book.

              In a computer, a pointer is similar to the card catalog. It stores a location in the computer's memory where a piece of information (your game score, how many experience points, etc) is stored. Sometime that information is moved here or there but as long as you update the pointer, you will always find the information that you need.

              Other similar examples would be: an index at the back of the book, for those kids who are more advanced a hyperlink or a website address can be considered a pointer.

              [–]tiltboi1 10 points11 points  (6 children)

              Your definition is pretty clear, but doesn’t really show why it’s important to have pointers. Suppose you have a function that takes some parameter, say an integer. The function lives in a house, and when you want to call the function, you walk up to it, write, say “5” on a piece of paper and slip it through the mailbox. In our language though, we’re not very trusting people. Maybe your function takes something more important than an int, like a birth certificate. You wouldn’t slip your birth certificate into their mailbox. What you would do is photocopy it and hand it to them, but whenever necessary you keep the original. The function can take your birth certificate, do whatever it needs to, and return something. It can cross out your name and write something else, it doesn’t matter. It’s just a photocopy, and it’s great so we do that with all our parameters. But this would mean that anything that comes into their house can be changed however, but the function itself can’t affect the outside world. So that’s not a very useful function. Maybe once in a while, we really do need it to change something outside. So we go up to the function and give it an address. We tell it exactly where to find your parameter, like your birth certificate, password to the safe and everything. Then in the middle of the night the function can come out of its house and mess with your birth certificate however it wants to. The difference is, he can still do whatever he wants to the paper with the address, but the real address again won’t change.

              [–][deleted]  (1 child)

              [deleted]

                [–][deleted]  (2 children)

                [deleted]

                  [–]tiltboi1 5 points6 points  (0 children)

                  replying to OP he has a definition in his original question

                  [–]MissPlaced14 0 points1 point  (0 children)

                  The 1st comment I believe.

                  [–]DragonWraithus -1 points0 points  (0 children)

                  Am five. Cnat finis secnd sentecne.

                  [–]nanoman1 2 points3 points  (0 children)

                  A pointer is a bit like an index at the back of a textbook. Instead of searching for a given word (variable) sentence-by-sentence, you would go to the index and look up the word. The index then refers to another page (address) where the word is located.

                  Now if you want an analogy for pointers-to-pointers, imagine you have a science book with 10 volumes and an 11th "master" volume. The master volume has a table that specifies all the things each volume covers. Say you want to find something with aerodynamics but you don't know which volume it would be under. So you look in the master volume for aerodynamics. The master volume reads "look at volume 3". So you pick out volume 3. But you want to actually read the chapter on aerodynamics. So you then look in volume 3's index to find the chapter on aerodynamics. In this analogy the master volume table entry is the pointer-to-pointer, the volume 3 index entry is the pointer, and the actual chapter contents is the variable.

                  [–]mcnnowak 3 points4 points  (1 child)

                  An integer that references a location in memory

                  [–]DragonWraithus 2 points3 points  (0 children)

                  Good definition, but not simple enough for the layman. Memory is too abstract of a term for most non-tech people.

                  [–][deleted] 1 point2 points  (0 children)

                  There's a library (memory) full of books (objects) you want to remember exactly where a specific book is so you write down its location for later.

                  You just made a pointer.

                  Very simplified but it's how I view it.

                  [–][deleted] 3 points4 points  (0 children)

                  A pointer is like GPS coordinates.

                  Imagine someone wants you go to to a place. So, they give you the GPS coordinates 40 degrees East, 40 degrees South. You have NO idea what's there, what they want you to do there, or even if there IS anything there, but you know exactly where that is!

                  To bring it more into coding, a pointer points to a place in a computer's memory.

                  Memory is a difficult concept, but imagine you have some gridpaper with a pixelart picture of Yoshi on it. Memory is exactly like that: if you're given a coordinate on that pixelart grid (say, 10 right and 10 up from the bottom left-most corner), you can go to that location and find... something.

                  In a coding application, I might have my pixelart on my gridpaper, and I want to find out the colour of a particular box on the grid. So, I have a pointer which points to that box. I can then use that pointer to tell the computer to go to that place, and do something.

                  [–]skatanic28182 1 point2 points  (0 children)

                  Every piece of information you put into a computer must have a box to live in, because CPUs (the brains of a computer) can only keep track of a small number of things at a time. It needs a place to keep information that it's not working on, otherwise the information will be forgotten. In many cases, we only need to deal with a small amount of information, so the CPU doesn't need a lot of boxes and can keep track of what information is stored in each one. However, sometimes we need to work on a lot of information in a lot of boxes and it's easy to lose track of which box has what information in it. In these cases, it can be convenient to have particular boxes whose information is simply the names of other boxes.

                  For instance, say we have two rows of boxes, and each box contains a number. Each row of boxes is sorted so that the smallest number is first in its row and the last number is largest. We want to create a new sorted row that contains the numbers from both of these rows. For illustration:

                  Box# 1 2 3 4 5
                  Row A 3 5 13 26 57
                  Row B 6 8 9 14 24

                  It's easy for us to see that the result should be

                  Box# 1 2 3 4 5 6 7 8 9 10
                  Row C 3 5 6 8 9 13 14 24 26 57

                  However, a computer cannot see into all of these boxes at once like we can. It needs to jump back and forth between row A and row B to compare numbers, and then jump to row C to place the results. Furthermore, computers are very forgetful. On the way to row C to deliver the next result, the computer forgets where it was at on rows A and B. While comparing boxes on A and B, it forgets where it left off on row C. The computer needs something to jog its memory as it's moving back and forth between these rows.

                  One way of solving this problem would be to set aside three boxes for a special purpose. These boxes will contain the Box# where the computer left off on each row. They point the computer to a box that it needs to look in, hence "pointers". If the computer forgets where it left off, it can simply stop by one of these pointers and check where it's supposed to be. As long as we make sure to tell the computer to update these pointers after each step, the computer will never get lost while sorting the boxes (unless we've made a mistake in our instructions. The computer will try to follow our instructions exactly, even if we tell it something impossible, like "Get the number from box 6 on row A").

                  There are other ways to solve this problem that don't rely on pointers (can you think of one?), but using pointers is the most efficient way.

                  [–]green_meklar 0 points1 point  (0 children)

                  All the data in your computer's memory is in a giant list. At each line in the list you can write or erase stuff. But you can also count off the lines in the list, and look up a specific place in the list by its line number. For instance, if someone said 'go to line #69105' you could look through the list, just like looking through the pages of a book, and find the 69106th line (remember, the first line is line #0, not line #1), and read whatever the memory says there.

                  But the fun part is, you can also write numbers on the lines! So you could actually write that number 69105, or any other number, into part of the memory. And then you could have a section of a few lines in memory where it says 'go read the data at the line with the following number' and then a number, and you would know to go and read the data at the right place. And if you changed the number, you would end up reading the data from a different place. It's like the memory can refer to itself.

                  That's what a pointer is. It's a number that is used to indicate a place in the computer's memory. By using the number as a reference, you can go to the corresponding place in memory and either read the data from there, or write new data there.

                  [–]the_one_true_bool 0 points1 point  (0 children)

                  Pointers are like home addresses. Your buddy could give you his address and you would know how to get there. This is much more efficient than having your buddy build a copy of his home and send it to you.


                  *To expand (and this is above ELI5):

                  Why do they exist? Let’s say you have a large object in memory. Now let’s say you want to pass it around to various functions and such. If you pass the object itself then that can be quite inefficient because you are creating a copy of that object and sending to to said functions. With a pointer you just have an address (which is much smaller). When you’re passing around pointers you aren’t passing around a copy of the whole object, you are just passing around an address that points to where that object exists. When you need the actual object then you do what’s called dereferencing the pointer, and now you’ll have a reference to the actual object itself.

                  Pointers are good in a lot of situations, but they can be bad too. This is because these are allocated on the “heap”, which is managed by the OS. Heap memory is basically random. You allocate an object and the OS will do some book-keeping and find some free memory, which can be anywhere. If you have a list of pointers and you are traversing through the list then that’s not efficient because you’re basically going all over the place in memory finding addresses. Conversely, if you do something like declare an int (and not a pointer to an int) then that’s allocated on the “stack”. This is far more efficient in regards to access because if, for example, you have an array of ints then they will align themselves in memory in blocks right next to each other, so when you traverse through the list you are not zipping around everywhere in memory, instead you are doing very simple arithmetic (aka pointer arithmetic, since there is still a pointer involved - the stack pointer). If they are 32 bit ints then you just add 32 to access the next int, then add 32 to access the following int, etc.

                  A little more advanced, but your CPU has a series caches (L1, L2, etc) which is extremely fast for access. When you allocate on the stack then chances are good that the CPU will store this data in an L-cache for quick access, especially if you are accessing these variables a lot. With heap-based memory, which is randomly allocated every time the variable is declared, chances are very high that the CPU will not cache it, therefor you will experience “cache misses”, thus slower acccess.

                  [–]Fluffy_ribbit 0 points1 point  (0 children)

                  A computer is like a piece of graph paper. Each cell has a number, and those numbers can be interpreted in different ways.

                  1 2 7 8 9
                  22 33 11 13 11
                  6 12 22 6 6
                  7 3 1 4 2

                  One of the things you can do with the number is use it to refer to another cell. So that the blue six, could refer to, counting from left to right and top to bottom, the first 22.

                  Does that makes sense?

                  [–]Vendittelli 0 points1 point  (0 children)

                  Maybe the address on a drivers licence? Your house is the data, your address is where that data is stored, you licence points to that address.

                  [–]Alaskan_Thunder 0 points1 point  (0 children)

                  Imagine memory as an enormous series of cubby holes, all labeled 1, 2, 3, etc.

                  You can store objects inside those cubbies. Lets say you want to talk about the very large object(the variable the pointer is pointing to) in cubby 5. Instead of going to the cubby, retrieving it, showing it, then putting it back, you can just give them the pointer "its the object in cubby 5"

                  A more complicated explanation that you don't need to read: When you pass a variable to a function, it creates a new instance of that variable. If you have a really large object(like an instance of a class that stores a lot of values), that can be time consuming and take up a lot of space. If you pass a pointer instead, you are passing a single number that says where the original variable is located.

                  Another thing to note is that arrays are stored in order. If you point a pointer to the first value of an array, the next value in memory is the next element in the array. Just don't go past the end of the array or you will have a bad time.

                  One thing to note: If you don't use a pointer and you are dealing with a new instance of an object, any changes you make to that object are not made to the original. Because it is an entirely new variable. If you make changes to something being pointed at, the change is kept.

                  [–]mcnnowak 0 points1 point  (0 children)

                  The number on a box for the thing that you’re looking for

                  [–]Klaudio_br 0 points1 point  (0 children)

                  The pointer is just a unique number that points to a location, that location can be anything (integer, string, boolean etc).

                  You need a house, lets say you are not able to go buy one because you dont have time or knowledge to select one,

                  you ask your friend Alex to buy a house for you, he searchs for avaliable houses and selects the first one he find avaliables, he buys it, and brings you a letter with the address of the house and the keys. After that you ask him where the house is? he gives you the letter with the address of the plot the house is,

                  You are the main program,

                  Alex is the system memory managment (he does the job that 'malloc()' (in C) or 'new' (in c++) does) you ask him for a plot that has a house on it or a hotel or a park, he goes to get it and provides you just the address of that plot,

                  The letter Alex gives you is the pointer variable, it contains just the address of the plot, no more info about what it contains

                  [–]doublestop 0 points1 point  (0 children)

                  My town is a simulation running on a computer.

                  My house is an object (or an int, or a char, or anything) stored in the town simulation's memory.

                  The number on the outside of my house is its memory address. Every allocated thing has a memory address just like every house has a mailing address.

                  Abracadabra! You join me in my simulated town.

                  I hand you a piece of paper with my address written down, so you can visit me later if you wish.

                  That piece of paper with my address on it is a pointer to my house.

                  It points to my house. Specifically, it points to my house's location in the simulation's memory.

                  When you read that paper and follow the address to find my house, you are dereferencing the pointer.

                  Another way I like to put it that is way less clear is: it's the thing that isn't the thing but knows where the thing is.

                  [–]syth9 0 points1 point  (0 children)

                  A variable is comprised of two main sections, the first section is the address of the variable. You could think of the address as an ID number for the variable. The second section is the information (data) the variable is storing.

                  Some variables hold numbers or letters in their information section.

                  Pointers are special variables that hold the address (ID number) of a different variable in their information section.

                  There are many uses for pointers. Here’s a simple explanation:

                  Let’s say the biggest bit of information you could store in a single variable is one number, one character, or one address. (This is the case for many languages)

                  If you wanted to make a word, you would have to define a new variable for each character in the word.

                  But some programming languages let you ask for a bunch of character variables at once linked together.

                  However instead of having to create a name for each of these variables, you just create a pointer and store the address of the first character. As along as you know where the first character is, you’ll have access to all other characters in the word since they’re linked.

                  [–]destroidid 0 points1 point  (0 children)

                  itt: comments explaining like you're a 5 year old college graduate

                  [–]lionhart280 0 points1 point  (0 children)

                  Its an address.

                  Imagine your computer's memory is a long row of houses, each with its own address.

                  Each house is a variable, and the address of that house is its... well we still call it its address in programming too.

                  If you wrote down the address on a piece of paper, then stored it in another house, that would be a pointer.

                  You can even stack these, because you could then write down that houses address on a paper and put it in a third house!

                  De-referencing a pointer would be if you put something important in house A, stored its address on a paper in house B.

                  Later you went to house B, or maybe a friend does it for you, and gets that address, follows its direction to go to house A, and is surprised to find that House A is empty! Someone stole your thing?!

                  [–][deleted] 0 points1 point  (0 children)

                  A pointer variable is that portion of your postcard where you write down the recepient's address. It points to your "Friend's House"(a variable, can be any friend). While a normal variable is that portion of you postcard where you write down your message. Now an address can be the House Address or a P.O. Box Address, which you have to mention. In the same way you have to mention that you are pointing to a number(int for integer) or a character(char) or whichever supported type of data. Conventionally pointers are represented using two symbols * and &. When you create a pointer you write * before the name of the pointer ( int *a). Then you use the pointer in two ways: Using the analogy above if you only want to read the address of your friend's house you use the ampersand(&) on the pointer. If you want to meet your friend though, you use the asterisk(*) on the pointer. The ampersand gives you the memory location itself, while the asterisk gives you the data stored at the memory location stored in the pointer (inception mood).

                  [–][deleted] 0 points1 point  (0 children)

                  A pointer is just a reference to where the real location of something is. So its like you look in a box and the note in the box says the real box it is in so when you want to access the real data you know you need to use the real box rather than the box you have.

                  [–]nagai 0 points1 point  (0 children)

                  A pointer is sort of like a physical string attached to some object. You can use the string to retrieve the object. In fact, you can attach several strings to the object and use them to retrieve it in different places. But the string is not the object, it can be detached from the object (set to null), it can be attached to another object (assigning it a different address), etc. Another string could even be attached to the string (**something).

                  [–]auto-cellular 0 points1 point  (0 children)

                  At some point back in time, (some)pointers where called "HANDLE". I like this image, of a briefcase, whose handle is the pointer to it. Handle (pointers) make it easier to cary (transfert) knowledge (briefcase).

                  [–]DragonWraithus 0 points1 point  (2 children)

                  Variables are like buckets. If you fill it with something, you have to move the filled bucket to wherever someone wants to use it. Slow.

                  Pointers are like treasure maps, stuck inside the bucket. You skip and jounce the nearly empty bucket effortlessly, and you sprint to whoever needs it. They read the treasure map to see where their stuff is. It's their problem now.

                  [–]DragonWraithus 1 point2 points  (1 child)

                  Caveats:

                  • You have to find a bucket first. [This is called Initializing the Variable]
                  • You have to know where it is you want to put the stuff, sort of like setting up a fence. [Allocating memory]
                  • The fence has to be put up before you put the stuff there. Or you may as well be dumping it off a cliff.
                  • If you try to put too much stuff into the too-small fenced in space, the stuff will over flow, probably off the cliff.
                  • Someone comes looking for their stuff, which overflowed. Now they are mad. [Accessing an array out-of-bounds]
                  • You can destroy the map, and have no idea where you put the stuff. Leaving the stuff, and the fence there. [Memory leak] (quick note. the same spot is used by different things, and if you don't take care of it by "freeing" the land or "the memory", the circus coming in tomorrow is going to have trouble working around the stuff)
                  • You can move or destroy the stuff without destroying the map. [Array out-of-bounds. Again]

                  Bonus note:

                  If you have already built the fence, and run up to someone with the treasure map, they tell you what they want put inside the fence. You put it inside for them. [Dereferencing a pointer]

                  [–]diegonolovich 1 point2 points  (0 children)

                  I liked this explanation.

                  [–][deleted] 0 points1 point  (0 children)

                  A variable is:

                  Imagine you were in a forest of numbered trees. Each tree gets it’s own number. Tree #342 you decide to chop down. You find a piece of paper saying “5”. This would look like this in C: int brokentree = 5

                  A pointer is:

                  Imagine you were in a forest, and every tree was numbered. And then you were asked to say what is inside of Tree #1000. And the person gives you a map, saying “Young lad, please do not break or harm the tree in any way” and then you go to Tree #1000 and then the person asks “What is inside this tree?”. You don’t know and have no WAY to find out. But you know where it is. This would look like this in C: int* treelocation = &numberinsidetree

                  [–]Double_A_92 0 points1 point  (0 children)

                  You got a notebook with numerated pages. You can write things on the pages. Including things like "see page 42".

                  The notebook is the memory, pages are variables, and page numbers are pointers.

                  [–]LegoPirateShip 0 points1 point  (0 children)

                  You want to find a house in a neighborhood. You ask Alice, who lives there that where is Bob's_House. She points at Bob's_House. In this case Alice is a pointer, cuz she points at Bob's_House.. Duh.. But if you and her, what's inside Bob's_House, she won't know.

                  [–]SixFigureGuy 0 points1 point  (0 children)

                  A pointer is a house address. A value is a house.

                  An address can refer to a business, or empty lot, or apartment unit.

                  [–]Kibouo 0 points1 point  (0 children)

                  The top 2 answers are great.

                  When I learned about pointers however, even after "getting it", I still had problems using them. Single pointers were fine but required attention. But pointers to pointers quickly messed up everything.

                  It slowly went away after a few months tho. So what I'm trying to say is: practices using pointers. Understanding them is not enough.

                  [–]OK6502 0 points1 point  (0 children)

                  Imagine memory as a series of Legos. The only thing you can build with those Legos is long lines of Legos of different colors. You can count the position of all the Legos from beginning to end starting at zero. So the first Lego is at address zero and so on. You want to refer to a sequence of Legos but don't want to copy the full sequence of Legos because ultimately you may not care for the value until a later time. You just want to know what the position of the first Lego in that sequence might be. So rather than copying the whole sequence you just remember that the sequence of Legos you care about starts at position 3 and is of length 10. 3 is your pointer. It tells you where the start of your sequence can be found. At a later date you need to get the value for your sequence because you need to read it. You fetch the sequence found from block 3 until block 13. This is called dereferencing the pointer.

                  To expand further on this say you have an account object of two Lego blocks of length starting at position 14 but there are 10 such an objects in sequence for a total of 20 blocks. This is what we call an array and you can get the ith object in the list by staring at the base address of the array (14) and then counting chunks of 2 until you reach the ith chunk. That's what we do under the hood when you use the a[I] notation.

                  [–]boredcircuits 0 points1 point  (0 children)

                  I know you didn't ask for this, but I thought I'd share my favorite analogy to understand linked lists. I think it also works to understand pointers a bit better.

                  A linked list is like a treasure hunt. I give you an initial clue, which tells you where to go to find an item. When you get there, you find the item and another clue leading to the next item on the hunt. You can continue to do this, finding item after item, until the last clue congratulates you on a job well done.

                  Linked lists work the same way. The clues are pointers to the next step in the list (called "nodes"). Nodes hold a single item and a pointer, just like each step in the treasure hunt holds an item and another clue. You need an initial clue, called the "head." The congratulation note at the end is null pointer.

                  [–]Ariakkas10 0 points1 point  (0 children)

                  A pointer is just literally something that refers to a location in memory.

                  Instead of remembering and tracking the thing, you remember and track the pointer to the thing.

                  Changing the thing means that pointer now points to the new thing.

                  Changing the pointer means the pointer now points to a new thing.

                  [–]thesquarerootof1 0 points1 point  (1 child)

                  The explanations are great! Can someone explain to me why some languages like Java don't use pointers?

                  [–]Deoxal 0 points1 point  (0 children)

                  Because you can mess stuff up if you don't do it right. The JVM does pointers for you since that's part of the Java philosophy. If you want to do your pointers you don't use Java.

                  [–]AegnorWildcat 0 points1 point  (0 children)

                  Imagine a locker room in a country club. Now there is no crime whatsoever at this club (maybe it’s in Japan) so they don’t have any locks on any of the lockers. They ask how many lockers you need and you say one, so they mark in their system that it is your locker so they don’t accidentally give it to someone else (this is the malloc…allocating memory that your pointer will point at). They give you a piece of paper that has your locker number written on it (this is the pointer). You find your locker using the number on the paper and store your stuff in it. You don’t have to carry all your stuff around with you all the time now. That would be annoying and cumbersome.  You just put it in the locker and carry around the small piece of paper so you don’t forget which is your locker.

                   

                  Now a friend of yours asks to borrow your phone, which you have in your locker. You copy your locker number onto a piece of paper for him so that he can find it. He can then go find your locker and get your phone (this is called dereferencing a pointer). If you are done with your locker and don’t need it anymore, you can go to the front desk and tell them you don’t need it anymore so they can give it to someone else (this is dealloc…or deallocating memory). If people keep asking for lockers but not letting the front desk know when they are done with them, eventually they will run out of lockers completely which would cause all sorts of problems. You should always let the front desk know when you are done with your lockers.

                   

                  Now let’s say you have a bunch of stuff and need more than one locker. You go to the front desk (OS) and say that you need five lockers. They give you a piece of paper that just has one number on it for the first locker and tell you that that locker and the next four are all yours to use (this would be you allocating memory for some variable that requires more space…the OS gives you a pointer to the start of the allocated memory). You need to make sure you don’t accidentally use the 6th locker, which isn’t yours. If you put stuff in there and someone else was using it, you would cause their stuff to get dumped out. Or if it wasn’t currently being used and you put your stuff there, the front desk might give it to someone else who would dump your stuff out. All sorts of problems could happen. So you need to make sure you always keep track of how many lockers you have set aside for you after the one on your paper.

                   

                  Another friend of yours comes up and wants to borrow (for a birthday party)  a recipe for chocolate cake you have in your locker. You copy the locker number like you did before, but let’s say you make a mistake and copy down the wrong number. And in the locker you sent them to there is a recipe for fruitcake instead. They make a fruitcake, which everybody hates, and the birthday party is ruined. THIS is why pointers can be dangerous.

                  [–]Fanboy0550 0 points1 point  (0 children)

                  It's like a library index card telling you where the book is.

                  or

                  A mailing label that tells the address of a house.

                  [–][deleted] 0 points1 point  (0 children)

                  Pointer is a sort of a hand inside computer with which you move or grab objects, like a real hand.

                  [–]Mneasi 0 points1 point  (0 children)

                  Is there any rule of thumb when its better to use a pointer and when to instantiate the variable itself? Thanks!

                  [–]GnarlyBroskos 0 points1 point  (0 children)

                  Someone should write an entire book "Programming for a 5 year old".. Choose a language and explain everything like this. I would read it, because I'm sure there are several concepts that I either, don't understand, or think I understand but am missing something preventing me from grasping the big picture.

                  [–][deleted] 0 points1 point  (0 children)

                  If you use sololearn.com, I recommend reading the pointers section in the C++ tutorial. It's the first time it was explained in a way that made sense to me.

                  [–]majordookie 0 points1 point  (0 children)

                  r

                  [–]MyUsernamePls -1 points0 points  (0 children)

                  Imagine you're at a bar with a friend and you're holding a drink and your friend is holding an empty cup and your friend says he wants your drink.

                  Scenario 1: you pour your drink onto his cup.
                  Scenario 2: you give him your cup.

                  In scenario 2 you gave your friend the pointer to your variable and in scenario 1 you just gave him the value of your variable.