Why learn pointers in C if I can just return values normally?
Posted by Sofiatheneophyte@reddit | learnprogramming | View on Reddit | 39 comments
I don't really understand the point of pointers right now. If my function can just return a value directly, why would I complicate things with 'int *ptr = &x'?
I'm new to C, and every time I read about pointers, I get the impression that it's just a complicated way to do something simple. Is there a real case where I'm forced to use them?
Playful-Sock3547@reddit
pointers feel unnecessary until suddenly you need them 😄 once you start working with arrays, modifying variables inside functions, dynamic memory, or anything low-level, they go from “why does this exist?” to ohhh, now i get it. the hard part is mostly the syntax at first.
buzzon@reddit
One reason for pointers is dynamically allocated memory. malloc function returns a pointer to the newly allocated memory. You are supposed to store the pointer, access memory via pointer and release it in the end via pointer.
DrShocker@reddit
There's a few reasons.
Firstly, you get big enough data and you simply can't anymore because you don't have the stack space for it.
Secondly, if you have multiple places in your code that need to modify the same data, it's often simpler to have 1 place where the data lives and you modify that one place rather than needing to keep hundreds of copies synchronized.
Thirdly, it's often faster to have 1 place in memory where you already set it up to store the memory and refer to that place again so that the CPU is more likely to cache the data you're accessing frequently whereas it can't do that if you have multiple copies of the data.
That said, it really just depends what you're doing if it's actually better to work with pointers or values. For small enough data sometimes the pointer is actually slower because it's bigger on your platform and has indirection compared to a copy.
teerre@reddit
Second point is pretty iffy, to not say downright incorrect
There are tons of material indicating that mutable state is the source of most bugs. Many languages either restrict or forbid it at all. It's certainly false to say you have to share to be able to write programs
DrShocker@reddit
I think you're maybe misunderstanding the issue I'm trying to describe. Certainly die hard functional programmers will point out you can write anything with zero mutable state. But I mean more so about having more than 1 source of truth for some information.
Even if ultimately you wanted to write code in a functional style and immutable in C, you'd likely end up using pointers rather than copying the data source thousands of times (depending on what you're doing of course)
MrMagoo22@reddit
Because data takes up physical space, and moving it around is a time expensive operation.
The analogy my college professor made with pointers is that a pointer is a slip of paper that has the address to your house on it. If you want someone to visit your house, you can use a pointer to give them that slip of paper and then they can look up that address and find your house. You could also allow someone to visit your house by physically uprooting your entire house and bringing it over to them, but usually you don't want to do that.
kalel3000@reddit
Because you dont have to reallocate space for runtime data in memory.....nowadays it probably isnt a huge concern....but back in the day every Bit mattered. Being able to pass references/pointers is super efficient too, way better than copying data from one memory block to another for absolutely no reason.
If you actually stopped and thought about how your programs utilized Ram, you'd understand why pointers are so beneficial
DonkeyTron42@reddit
It's a still a huge deal for for many applications. Imagine how ridiculous it would be to write a Windows application that does something like pass around copies of dereferenced Window handles that can be 10's or 100's of MB in size.
kalel3000@reddit
Fair enough, I should have specified I meant mostly in regards to whatever small introductory c++ project the OP was playing with.
You are obviously correct! I just misspoke
AlwaysHopelesslyLost@reddit
Why learn multiplication when you can just add a bunch?
ILoveDogsDontUToo@reddit
This is just stupid. The experienced programmers here aren’t impressed and you’re just being rude to someone new.
AlwaysHopelesslyLost@reddit
Providing an analogy is not rude. You assumed I was trying to be rude. I was trying to provide the simplest possible explanation to help OP understand why.
saffash@reddit
Be nice now... They are new!
YetMoreSpaceDust@reddit
Pointers are the only mechanism in C to share memory between different two functions, and it's common to want/need to do that even if it doesn't seem obvious at first.
consider this code:
This will print 2 - the x that you passed into the function is changed inside the function, but that's only visible inside the function.
Often that's exactly what you want (in fact, there's a school of thought that all programs should behave this way and only this way - that's called "functional programming" but unfortunately C isn't expressive enough to support it). Some times it isn't, and so instead you want to share the memory:
This prints "6" - the change inside the function is visible outside the function.
This is a simplistic example (it'd be rare to want a function to change the value of an integer in its calling function) but when you get into structs and things, you often need the calling function to be able to interact with its caller this way.
Pointer syntax is kind of intimidating, but remember that your computer's memory is just one big giant array. Each variable that you can interact with has an "address" which is an entry in that giant array. "&" means "get the index of this memory location" and "*" means "update the memory at this location". The second example is maybe easier to understand using array syntax:
Here I'm "pretending" that memory is a global array (except I'm not really pretending because it actually is!). I chose an arbitrary location of 26 (in practice the compiler picked one for me when I declared int x = 2) and then passed this index to the function. This is what &x does: it asks the compiler to give back the arbitrary index that points to "x" in memory. The call
"dereferences" this "pointer" just like
does, I'm just making it look more explicit.
lurgi@reddit
If you want a function to change a value that is passed in, you have to use a pointer. If you want a function to take or return a very big struct, you probably should use a pointer for performance reasons (it's a lot easier to pass a pointer to a 4K chunk of memory than to give it a copy of the actual memory).
Many data structures (linked lists, trees, etc) would be impossible without pointers.
USMCLee@reddit
One of the things that learning to program with 64kb of memory taught you.
Beregolas@reddit
I simplify a bit, but I think it's more important that you understand the rough concept, than that I'm being 100% accurate:
Data is not magic, it lives somewhere in your computer. In our program, we have two different kinds of memory: The heap and the stack. The stack is what your current function has to work with. Everytime you call a function, another "level" gets added onto the stack. If you return, that level gets deleted. This is what a stackoverflow is: If you call too many functions, you fill up the memory reserved for the stack -> it overflows. The heap is bigger, and freely accessible from all function calls. But you need an address, a pointer, to know where data is.
Your question boils down to: Why can't we pass everything by value, but we need to pass some by reference. Some ideas as to why:
Everytime you pass by value, you need to copy that value. Because the stack is volatile (your stackframe gets deleted after return) you constantly need to read and reweite values. This might be fine for a single integer (basically pointers are also integers), but if we are talking about a large struct or string (char array in C) that contains kilobytes or megabytes of data, copying that for every function call suddenly becomes slow and cumbersome
You cannot let the caller modify the original, if you pass everything by copy. A common pattern is, to give a function a pointer, and the function the mutates something inside that pointer. You can't do that if you copy the value, because then... they are two different values; they just start out being the same.
Pointers are often used to show, that nothing is being returned. Simply by setting the pointer to 0 -> a NULL pointer. Other languages have the same concept, just with keywords such as null or nil. This is sometimes a bad pattern, but sometimes we want to do it
There are many other reasons, but pointers are important. Go look up passing by value vs. by reference. This is also important to understand for languages that don't expose pointers, like Python or JS. Internally, they also use heap and stack, and passing by value and by reference. If you don't understand when which occurs, you WILL trip up and make expensive mistakes down the road.
p0cale@reddit
Apart from large datasets where pointer makes sense; what is the difference versus using global variable, accessible everywhere. There too a function don't need to return anything yet data is accessible in function and caller?
epic_pharaoh@reddit
(take with a grain of salt, it’s been a bit since I read the theory on this)
You could have everything be global variables, it all depends on how you want to pack and organize the code.
If you are working in multiple classes, with multiple scopes, and plan on sharing pieces of your code, using all global variables becomes messy and unsecured (stuff like overlapping variable names) very quickly.
Basically it’s a best practice thing. For more in depth info look into namespaces and scope in C.
FatDog69@reddit
C is a very low-level language. It is close to the hardware.
If you are writing code for a small device - pointers can help your code run faster on devices with small amounts of memory and slow processors. (Ever hear of "Cell Phones" and "Tablets"?)
Pointer use is probably your number one source of core dumps/problems/crashes. Some programs like Java made a big deal that it refused to let the programmer do pointer logic. But when it works it can run fast with a smaller memory footprint.
ILoveDogsDontUToo@reddit
There are many good answers here. I’ll add a more basic answer. C is used in applications where right memory management and speed are paramount. As you’re learning, C lets you address and manipulate memory directly - something other modern languages like JS and Python don’t allow.
So what you’re learning now is the basics of that memory address referencing. It will get more complicated and more useful later.
For now, just keep grinding through the lessons. Sounds like you’re doing great.
Leverkaas2516@reddit
User lurgi's comment gives a great answer. But I'll address this point:
C is not built to save you from complications. Its purpose is to allow you to write code that does exactly what YOU want to do, whether it's complicated or not.
dyslechtchitect@reddit
If you want to return a list from a function you can only return a pointer to it's first element
huuaaang@reddit
Main use is for structs. But also any blob of memory you might want a function to fill in. Or maybe you just don’t want to make a copy of a large object every time you pass it to a function. A lot of variables aren’t simple 1-8 byte values.
ironnewa99@reddit
Shitty simple thought (in 4chan style format) for it is:
-why duplicate when you can give an address to memory instead.
Examples:
-consider a db with a billion users, don’t copy the db, just point to the address instead
-you don’t need to move the whole house when you want a plumber to fix your toilet, you give him an address and he comes and fixes it.
HolyPommeDeTerre@reddit
Returning value is copying the value. Returning a pointer (a reference) is pointing to the place the value is.
In the example of a Book, let's say someone want a book that you have. Copying the book vs showing where the book is. The first one will take a lot of time to you. The other one won't.
Aggressive_Budget368@reddit
I'm new to coding too and also currently learning C++, so correct me if i'm wrong. Well there are many reasons why you should understand the basic of pointers. I'm not talking about mastering it, but you have to know where and when to use it, it will certainly help you when switching to other languages, such as Java, Javascript. Talking about C++, pointers are needed when you want to learn about advanced feature, like object-oriented programming or especially, data structure and algorithm, you gotta meet a lot of cases using pointers, for example linked list, tree, etc. Even if you don't see pointers in other languages, such as Python, Java, they are still working behind the scenes.
HashDefTrueFalse@reddit
That's all I can think of for now, but there's almost certainly things I've left out. Pointers are important.
Far_Swordfish5729@reddit
If x is something small like a primitive variable, you wouldn’t. Eventually though x will be something like a three dimensional array of RGB pixel values the size of a full bitmap image and you’ll be trying to do a transform on it. It might also be a c++ vector of large database records you need to process. In those cases you will not pass and return copies of the data because it’s wasteful. You’ll pass a pointer to it by value so you can move it around a singleton copy of the big data without accidentally moving the caller’s current place in it as you might if you passed it by reference.
A lot of what we do with pointers (abstracted in OO languages) is get a large chunk of data, build organizing structures on top of it using pointers (accounts by id for example where the index being build is a hash table of int id, int memory address pointer) and the process it. I can store pointers all day without blowing my ram. I cannot store copies of the actual text data. All our data structure tricks do that except for arrays. With arrays, because every piece is the same size, you can just jump the pointer to whichever element you want. Structs are similar because the sizes are known at compile time.
Your other main uses are for event handlers (pointers to functions) and to store OS resources like file handles and mutexes. The OS function gives you back a number that fits in a void* representing what you asked for and you hand it back when you want to do something with it.
Feisty_Manager_4105@reddit
Returning a value "directly" returns a copy of the value. Modifying the return value does not modify the original variable.
One of the use cases of returning pointers is if you want to modify the variable "x" with logic that is not visible / accessible to this function. If you returned by value, you would have to modify this copy and then write another function to update x.
If you returned a pointer to x, you could dereference the ptr variable and modify x directly thus avoiding the extra functions and also potentially avoiding having to declare x as global variable.
Another common use case of returning pointers is if your pointer is pointing to a struct. If your struct is bigger than ( 4 / 8 bytes) it is inefficient and slow to return a copy of a big struct.
This is just one case, pointers are very useful. Yes you can avoid using pointers, but that would make you a very inefficient and frankly terrible c programmer. Even high level languages like C# use pointers under the hood.
_TheNoobPolice_@reddit
Pointers are not only essential to mutate variables that are passed-in as params without returning a value explicitly to the caller, but also they are incredibly convenient. You can use local pointer data types within a function as aliases for complex data structures when passing them into other functions, and you can create structures of pointers explicitly for the purpose of grouping other pointer types together to pass them around as one one parameter. This is typical of OOD code in C
cartrman@reddit
Sounds like you need to learn pointers in C
ReddiDibbles@reddit
You're getting funny answers because your question is "Why should I learn C when I'm learning C". Not understanding the value of using pointers is normal but the answer is probably just to keep learning pointers.
No_Report_4781@reddit
Do you need to use the contents later? Then you’ll create a variable to hold it, and send a pointer to the function so the value of the variable will be updated directly. This works well when handling lists and arrays
If you don’t need the value later, and you will only use it as it is returned from the function, then you don’t need a pointer.
Poke_Gamerz@reddit
One reason is to use less memory, when u use a pointer the pointer object is always an integer, the type that you specify is for the compiler, since the pointer is always internally and integer, it's size in the memory is 8bits.
An example of this being useful would be Suppose you want to operate of some array of integers, an array may have 1 element or 100 elements, say it has a modest 20 elements, then the array itself would be of size 8x20=160 bytes. If we were to pass this array as it is to a function then the function would create its own copy of the array and that array would also accupy 160 bytes in the memory. If we had used a pointer instead of this, we could simply point to the address where the array is stored, so it would take only 8 bytes to actually pass the array to the function.
howzai@reddit
they are memory control, you assign memory address through pointers - pointers are not about replacing returns
Educational-Paper-75@reddit
Exactly, a function can only return values not variables.
rupertavery64@reddit
Because sometimes you don't return values.
Dk000t@reddit
lol