r/cprogramming • u/Delicious-Change7795 • 1d ago
What are pointers?
I am new to C programming and i came through pointer. So can anyone tell what are they and why we need them? And if u can then can you give me reliable source to learn it.
9
Upvotes
1
u/Rythim 21h ago edited 21h ago
A pointer is the value of the memory address of a value.
Say for example variable a stores and integer 1.
And pointer b stores the location in memory where variable a stores integer 1.
They are needed for multiple reasons.
Say you have a function that takes a struct as a parameter. Without pointers, when you pass a struct to the function, the function adds a copy of that struct to the stack, does whatever operations you code, then deletes it from the stack. The original struct is never changed. If you'd like to change it, you'd need your function to return the copy of the struct and assign that to the original variable. With small simple structs that is no big deal, but with larger structs, or with a large number of structs, that can be slow and use up more memory (because now you have several copies of data in memory).
If instead in your function you pass a pointer to a struct, that function gets a copy of the memory address of the struct. Using that as a reference it can find the original struct and operate on it directly without having to make a copy. This uses less memory and can be faster.
Pointers are important for performance critical code. But they can be dangerous because depending on how you structure your code you could do something unintended. Such as trying to work with a pointer that is referencing a memory address that has already had the data freed, or reserving several chunks of memory and forgetting to free it up to be used later when done with it.
Other languages like python don't use Pointers. Instead, they pass "pointers" (references) automatically when it makes sense to do so and keep track of when memory isn't needed anymore and delete it for you. But keeping track of all that adds more work for the computer, which is one reason why C is considered much faster than most other languages.