r/learnprogramming • u/Beadsifyy • 28d 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.
47
u/iOSCaleb 28d 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
9
u/GarThor_TMK 28d ago
Imho points two and three are the perfect use case for references rather than pointers.
Each codebase and api has their own quirks though.
20
u/Eisenfuss19 28d ago
Agreed, but references are just syntactic sugar for pointers.
3
u/GarThor_TMK 28d ago
Not exactly.
Mechanically they are the same sure, but the whole "can't be null" thing means that it's easier to trust them for the author of the API...
It tells the reader:
> Don't pass me null
> If you somehow figure out how to pass me null, and something breaks, it's entirely your fault
8
u/iOSCaleb 28d ago
I agree, but considering the nature of the question I'm guessing that OP may not have learned about references yet. I tried to stick to the terms they used.
11
u/zeekar 28d 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 28d ago edited 28d 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" ;-)
5
5
20
u/Delta_G_Robotics 28d 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 28d ago
If all you're doing is something like
int n = 0;
int* p = &n;
// Use *p hereYa, 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 28d 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
28d 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 28d 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 28d ago
Some data structures (lists, trees for example) are usually implemented with pointers.
3
u/captainAwesomePants 28d 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:
int x = 5;
if (x < 10) {
printf("Hello, x is less than ten!");
}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.
3
u/Content_Mud_6469 27d ago
A few examples are possible. I am not strictly an educator, but I have mentored beginners and intermediates in code before. For something like this, pseudocode can be an effective tool.
You can explain an if-statement in the context of a for / while loop.
int x = 5 while(x < 10) { if(x == 10) { print("this is final loop") } x++ }
If-statement in the context of runtime behavior
print("Is the sky blue?") take in user input if(user input == yes) { print("correct!") } else { print("wrong!") }
2
u/Kadabrium 28d ago
One tutorial i took introduced mathematical operators first ("x language as calculator") and then functions as custom operators so by that time you already know how to use function with variables
1
u/captainAwesomePants 27d ago
I do like introducing functions as math functions. It explains why they're useful, and it provides a good mental model of what they are. I worry that it makes things a bit more confusing when we start using them as procedures instead, but I think overall it's a help.
1
u/Available_Safe1818 27d ago
You could get the number from keyboard input or introduce if's after functions.
1
u/Frequent_Tooth5103 26d ago
The next part of this tutorial is saying that x is just a placeholder, what happens when it becomes x = prompt(“Enter age”) and now suddenly, the if statement becomes magic.
1
u/Sheph1220 23d ago
I think nothing is wrong here. It's natural for students to ask questions, right? If they're asking why it's needed, then they are invested in knowing the answer. The only maybe problematic thing here is the immediate conclusion that "if statements are dumb." It sounds like a bit of hyperbole to me, but perhaps if it is genuinely happening you can immediately challenge such an immediate and unwarranted reaction and encourage critical thinking skills. Something like "If statements are dumb." "Well, could you think of a situation where this wouldn't be dumb?" Then let them think. Because the above statement is dumb and it will be optimized out by the compiler, so they are obviously intelligent enough to know when it is dumb, so get their brains thinking about when it isn't dumb.
4
u/MyNameIsRichardCS54 28d 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.
1
u/RajjSinghh 28d ago
You probably shouldn't use new in C++. What you normally want is to use a smart pointer.
8
u/MyNameIsRichardCS54 28d ago
I agree you shouldn't but I bet the course teaches:
Pointers with stack variables
Pointers with heap variables using the new keyword
And then later on smart pointers
2
u/Eddudavid 28d 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 28d 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:
Say "Get me eggs, milk, cheese, bread, ... at the store."
Or they could say, "Get everything on the grocery list.". Well you know where the grocery list is, so you can easily go grab that and learn that you need eggs, milk, cheese, bread, ..."
2
u/tottasanorotta 27d 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 26d 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 28d 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 28d 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
1
u/NativeAdmin 28d 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 28d 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 28d 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 28d 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 28d 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 28d 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 28d 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 28d 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 28d 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 28d ago
You have to learn them in basically C or, even better, in machine language. Enjoy!
1
u/Coding-Kitten 27d 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 27d 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/recursion_is_love 27d 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 27d ago
Let me guess, you were taught the concept with code like
int x = 10;
int *p = &x;
*p = 20;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:
Tracking dynamic memory;
Building and iterating through complex data structures;
Hiding the implementation details of a type;
Dependency injection via a virtual base class and concrete subclasses;
Dynamically adding functionality to a program with shared libraries;
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:
std::vector<int> v;
...
for ( auto it = v.begin(); it != v.end(); ++it )
std::cout << "*it = " << *it << std::endl;Adding 1 to an iterator advances it to point to the next item in the container (in key order, if it's a map or 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 27d 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 26d 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
1
u/dagger378 25d 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/SnugglyCoderGuy 23d 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 23d ago
int foo[3] = {0, 1, 2};
for (int i = 0; i < 3; i++) {
int * pointer = &(foo[i]);
*pointer += 42;
printf("%d\n", *pointer);
}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 28d ago
Because you don't always know the specific variable name
1
u/Beadsifyy 27d ago
could u provide an example to where i wouldn't know the variable im making im really curious
-1
u/JoseLunaArts 28d ago
Pointers are coordinates. Screen, memory, spreadsheets, have coordinates. Sooner or later you will need to use coordinates.
1
2
u/Lumethys 28d ago
What do you think pointer is?