r/learnprogramming • u/Beadsifyy • 24d ago
confused with pointers in c++
I dont see the need for pointers when we could just write down the normal variable name, im genuinely so confused.
34
Upvotes
2
u/Lumethys 24d ago
What do you think pointer is?
47
u/iOSCaleb 24d ago
There are several reasons to use pointers, including but not limited to:
- the value of a variable might change over time; you want to say “use the value stored here, whatever it happens to be” rather than specifying one specific value
- instead of passing in data, a caller wants to tell a function where to store data
- the data in question is large enough that making a copy just to pass would be inefficient; for example, an image can easily require tens of megabytes, and making a copy just to send to a function would be slow and use too much memory unnecessarily
- in C++, you always need some sort of pointer or reference to access data stored on the heap
- pointers facilitate flexible data structures; for example, each element of a linked list contains a pointer to the next element, which makes some operations (like insertion or deletion) very fast because you only need to manipulate the next pointers of two elements
11
u/zeekar 24d ago
Pointers let you access variables that don't even have a name, variables you don't know you need until runtime because something at runtime determines how many you need. You can't declare an array without declaring how big it is, so pointers are the only way to have a collection of things when you don't know ahead of time how many things there will be.
44
u/corpsmoderne 24d ago edited 24d ago
"I don't see the need for postal adresses when you could bring the whole house to the poster each time they need it" ;-)
20
u/Delta_G_Robotics 24d ago
Eventually you will think that you want to be able to use a variable to hold the name of another variable so you can decide at runtime which variable to use. And then you will understand why we have pointers.
8
u/carcigenicate 24d ago
If all you're doing is something like
Ya, there won't be any benefit over just using
n. You need pointers to access dynamically allocated memory, though, among other cases. The need for them isn't apparent until you start doing more complicated programs.16
u/teraflop 24d ago
This is like saying "why do we need integer variables when we could just write all the numbers directly in the source code".
You need integer variables because you might want the same program to operate on different numbers at runtime. Similarly, you need pointers because you might want the program to operate on different memory locations at runtime.
Imagine writing a function that finds the sum of all the numbers in an array. If you write the array name directly, the function will only work on that particular array. So if you wanted to be able to find the sum of ten arrays, you would need ten functions, all with identical code (except for the different array name).
If you pass the array location as a pointer, you can write a single function that works on any array.
More generally, a big part of programming involves dealing with data structures, and most of the useful data structures involve pointers.
6
u/[deleted] 23d ago
Imagine you have a string variable that contains a 255 letter string, and you need to pass it to a function. You can pass the string - 8120 bits. Or you can pass the pointer to it - 32 bits.
3
u/minneyar 24d ago
In C++, you need to be aware of where in memory your variables are allocated. There are two places you can allocate memory: the heap and the stack.
What you're thinking of as "normal" variables are ones that are allocated on the stack. They are allocated when you declare them, and they are automatically destroyed when the scope in which they were allocated exits. In other words, if you create a variable on the stack in a function, it will be destroyed when the function returns.
Sometimes you need to allocate memory that persists between different scopes, so you can pass it around and keep using it even after a function returns. To do that, you have to allocate it on the heap. But then the question is: how do scopes outside of the function where it was allocated know how to find it? The answer to that is through a pointer, which literally points to the location in memory where the data exists. You can pass around the pointer and every other function that has it can access that same memory, because data on the heap is not automatically deallocated. The catch is that you have to remember to deallocate it yourself when you're done with it; if you don't do that, that's what causes memory leaks.
3
u/Lopsided-Dare-8119 24d ago
Some data structures (lists, trees for example) are usually implemented with pointers.
3
u/captainAwesomePants 24d ago
Meta question for more experienced devs and educators:
I see this sort of thing a LOT, especially with children but also with college students, mostly with folks following a curriculum and not self-learners. We tend to introduce things with examples that don't show why something is useful. For example, I see a lot of examples of how to use an if statement that look like this:
And then a student will inevitably say "that's not very useful, we already know that x is 5. It's definitely less than 10. Why not just print the line? if statements are dumb."
What needs to change with education here? We want it to immediately be clear how a tool is useful, but it's hard to come up with examples that show how useful things are that aren't also unnecessarily complicated for demonstrating how the tool is used.
4
u/MyNameIsRichardCS54 24d ago
You need pointers to access the Heap memory. They're the only way to access it. So when you create heap variable with the new keyword.
2
u/Eddudavid 24d ago
With pointers, you pass the reference to the memory address of said variable.
Imagine that you have an int, call it "A". "A" allocates 4 bytes of memory. Now, you need the same value at some other place, lets call that "B". If you create a new int, and just assign the value, it will create a new 4 byte variable. But, if you pass the memory reference, your new "B" variable will point to the memory address of "A". You just saved 4 bytes ( yay ). Also, when "A" is updated, so is "B".
Many modern programming languages do this automatically, and sometimes you have to break the reference. But C++ is very low level, and you have to create these bindings by hand. This is one of the fine examples why you can optimize so well in low level languages.
2
u/Simpicity 24d ago
Sometimes its important to be able to reference data or a set of data easily. For example, let's imagine your parter is sending you to the grocery store. They have things they want you to buy.
They could:
2
u/tottasanorotta 23d ago
A pointer is a special variable that can interpret its value as a memory address and access the data stored in that memory address. A normal variable can also hold a memory address, but it can't access the data that is stored in that address.
One nice use case is when passing data to functions. Normally the C++ compiler will just create a copy of the variable for the duration of the function, so when the function returns, the copy of the variable inside the function will also cease to exist. But if you pass a pointer to the variable instead, then you can directly modify whatever value exists in that memory address and when the function returns those changes are still there.
It's all quite confusing at first and it requires some practice to understand well, but pointers are really really useful and important.
2
u/mikemontana1968 21d ago
most of the time knowing the value of a variable is what you want. Thats straightforward enough. Sometimes you have a variable thats actually a structure of data - say a Name, Address, City, State. If you have several functions that use that structure (PrintPerson, SavePerson, FindPerson, DeletePerson....) it becomes computationally inefficient to keep sending the whole structure to each function when the compiler already knows what address its at. An address is only 4 bytes, and the structure might be 512 bytes. Why not just send the 4 byte address instead? In this case, its a computational efficiency (and thats really important)
If you get the address then you have a "pointer" to where the structure is in memory. Eventually you will need to put data in those locations which means you have to work with the "pointer" in the opposite way, you are de-refrencing that memory.
After you work through the idea that passing 4 bytes is better than 512 bytes, you can broaden your view to think of lists of Persons. Say you have 1,000 persons in a list, and you want to "Find" a person - its totally dumb to pass 1000 x 512 bytes when all you really need is those original 4 bytes, and the knowledge that at every 512 bytes the next person's data is there in memory. In this case you're working with a pointer to a pointer (sort of, let me slide on this technical oversimplification). Using this method you can start to do Inserts, Deletes, Sorting of the Person List without having to pass the entire list every time - just pass the address of the structure to change, and its size. This is SUPER efficient
2
u/fasta_guy88 24d ago
Pointers (or references) are necessary when working with more sophisticated data structures, like linked lists and trees. Operations on these structures often re-organize the connections between one part of the structure and another, which is easy with pointers, and almost impossible otherwise.
2
u/EquipLordBritish 24d ago
In order to understand why pointers are important, you have to better understand the stack and the heap. If you are just starting to learn programming, you will likely not have been taught about this yet, and will be exposed to it later. It is enough to say that using pointers is extremely important for efficient code.
Of course, there are plenty of articles online that describe these things, so you can always go reading ahead on your own.
https://icarus.cs.weber.edu/~dab/cs1410/textbook/4.Pointers/memory.html
https://circuitlabs.net/labs/c-stack-heap-memory-visualizer-learning-tool/
1
u/Dazzling_Music_2411 24d ago
Very true.
1
u/NativeAdmin 24d ago
A pointer in C++ is a variable that stores the memory address of another variable rather than a direct value. Declared using the asterisk (*) operator and initialized with the address of a target variable using the address-of operator (&).
1
u/RajjSinghh 24d ago
Pointers tell you where a variable is. That's very useful in some contexts.
Imagine you have a very large struct that you want to pass to a function. Without a pointer or reference, that whole struct gets copied into the function. Passing a pointer or reference would save you time since you don't have to do the copy. Same thing with arrays since an array is a contiguous block of memory with a pointer to the front.
1
u/elperroborrachotoo 24d ago
As a beginner in modern C++, you need pointers very rarely.
However, the implementation of many standard types and libraries rely on them.
Why do you think you need to understand pointers right now?
1
u/NaturalTechnician737 24d ago
A pointer is a reference to a memory address 'A'.
The type of a pointer informs how many bytes of the memory beginning at a reference address 'A'.
Many things exist outside the scope of "self", young Padawan. Ignore them all, learn C, then praise Scandinavia for all the beautiful work-arounds.
1
u/Narrow-Low-3137 24d ago
Without pointers, you would only have access to the stack. You need pointers for dynamic memory allocation on the heap.
I think this video is pretty relevant: https://youtube.com/watch?v=lQCLAKfcYI4
1
u/Toxonomonogatari 24d ago
You probably don't see the need for working with pointers and references because you're not doing system level programming, and that's fair enough. If you can write code to do what you want to achieve without thinking about pointers, that's fine!
To the best of my knowledge, most programmers don't need to think about this. If you're working with C++, you'll probably have to think about it at some point. You'll learn how to reason about it when you're learning about assembly languages, operating systems, compilers, etc. I wouldn't worry about pointers and references in isolation.
1
u/frnzprf 24d ago
One reason would be that it's faster to copy a pointer than a larger data structure, in case you are in a situation where you have to copy around data to different places.
There are also some data-structures that require memory to persist after the function in which it was allocated has returned. Then you use pointers to access this memory. If you don't know what "allocating memory" means yet, then maybe you'll learn that in a later lesson. You need it for example, when you want to implement a Linked List.
1
u/blue-cheeso 24d ago
Regardless of all the fancy tricks you can later do with pointers. The main thing they allow you as a newcomer is passing a variable value by reference, you normally pass this by copy. The difference between pass by copy and reference is a important concept to know in programming in general.
Later you can use them for dynamic memory allocations and more.
1
u/Derekthemindsculptor 24d ago
Because you're probably working with very simple primitives. What happens when your data object is a massive chunk of data? Like a string? You want to move and rewrite huge chunks of memory? Or leaving that data on the heap, and simply passing around a dirt cheap pointer?
Although, you've said "variable name" which makes me think you don't know what pointers or variables even are. I'd work on your fundamentals. What primitives are and how they exist in memory.
1
u/Lovely_Cygnus 23d ago
You have to learn them in basically C or, even better, in machine language. Enjoy!
1
u/Coding-Kitten 23d ago
How would you create a list of things by just "writing down the normal variable"? Be it linked lists or dynamic arrays, whichever.
Imagine you're making literally anything that needs a list. A cart in an online store that holds every product someone wants to buy. An inventory in a videogame of everything the player holds, a list of waypoints in a map/navigation app, a feed of posts in a social media platform. How would you do that?
At their most fundamental level, computers are about having a big collection of numbers & manipulating them. If not a number to hold a value, you'll have a number to hold where a different number is. This is fundamental to the very core of von Neumann computers that there's no other way to do things. Variables are a C++ thing, pointers are a computer thing.
1
u/regular_lamp 23d ago
Most people have no issue with arrays and indices. A pointer is like an index in that sense.
So the question is a bit like: "Why would I use an index variable with an array if I could just write a[1], a[2], a[3]?"
1
u/schungx 23d ago
Yes you can. But there will be a lot of variables you need to remember names for.
Think of your road without addresses. You have to remember hundreds of Bob's home, John's home, Mary's home, the house that used to be a barber but now is a bookshop, etc.
1
u/recursion_is_love 23d ago
It is not strictly need but it is good to have. The CPU have instructions that give high performance when using address of a memory (that's a pointer).
Learn about The Von Neumann architecture if you want to know more.
1
u/SmokeMuch7356 23d ago
Let me guess, you were taught the concept with code like
or something like that. Nobody uses pointers like that, and if I could purge that example from every textbook and tutorial I would.
The chief uses for pointers in C++ are:
Just to name a few. Unfortunately, useful examples of these are kinda big for a Reddit comment.
Most of the use cases for dynamic memory and complex data structures are already handled by the standard containers (
map,vector, etc.). There's a special kind of pointer called an iterator that's used to traverse through containers in order:Adding 1 to an iterator advances it to point to the next item in the container (in key order, if it's a
mapor something like that), so it behaves like a pointer into an array, even if the items are not physically adjacent to each other.1
u/abd53 23d ago
The variable name is just a human readable marker for the memory region storing an information, which the compiler strips away. And variables are limited to their scope. Now, what to do when you want to pass some information from one scope to another or keep some information beyond the scope is created/assigned at? You need to locate the memory region storing that information. Pointer is that raw memory address.
1
u/SillyLilGoose69420 22d ago
well anytime you want to use an array or pass it to a function youre using pointers whether its copied or not, indexing an array is pointer arithmatic the compiler does for you.
you can use them for self referential data structures like a linked list.
it has nothing to do with the stack, both the stack and heap are in memory, you can have pointers point to data in either. you can pass pointers to objects on the stack or the heap to functions.
also if you want to modify an input parameter you can use pointers.
for larger types you can pass by pointer to avoid the function copying all of the types data on entry which can be a lot more expensive than copying a 64bit pointer (depending on the architecture) and dereferencing it within the function.
classes implicitly pass pointers, its how methods modify the class data (the same concept as before, "if you want to modify an input parameter", except the compiler passes it implicitly, methods are free functions with an implicitly passed pointer).
1
u/razorree 22d ago
read about referencing (to be confused more :) )
1
u/dagger378 20d ago
I can tell you with 100% what you need to do at this juncture in your learning:
Pick an assembly language, learn it, and write some non-trivial programs in assembly.
Then return to C/C++ after your assembly adventure. I promise it’ll make more sense.
1
u/Paxtian 20d ago
Implement a data structure that has the following behavior:
I want to be able to store a series of integers. At any point, I want to be able to add to the series or remove from the series.
You can't use the STL.
1
u/SnugglyCoderGuy 19d ago
If you want to share a resource with many things, like a database client or a store of data, then you give the many things a pointer to it so they are all working with the same thing instead of their own local copy.
1
u/SeriousPlankton2000 19d ago
In this case I'm accessing foo[i] without re-calculating the address each time. Because it's an int I could make a copy (if I'd not intend to modify it), too. But for strings in general it would just be wasteful to not use pointers.
0
u/atarivcs 24d ago
Because you don't always know the specific variable name
-1
u/JoseLunaArts 24d ago
Pointers are coordinates. Screen, memory, spreadsheets, have coordinates. Sooner or later you will need to use coordinates.
1
u/deltageek 24d ago
Let Binky educate you
https://youtu.be/i49_SNt4yfk?is=Nvw9gHsqTlcJqPdr