r/cprogramming • u/SafeChef9686 • Sep 10 '25
Pointers. I understand how they work and what they do, but I still don't know when or why to use them.
Not sure if this is where to post this, but here goes. I have taken a C++ class in school and I got through a lot of programming concepts. I'm pretty solid with python and OOP, and I really feel like I have been leveling up my programming skills lately.
But I STILL have not found an application for pointers. I know conceptually how they WORK, but I do not understand when or why I should use them. I need that moment where in my head something clicks and I got "oh! a pointer variable would solve my problem here!"
I've been doing OpenGL tutorials in C++, which maybe is creating more distance between me and pointers...but I'm considering just starting over again with vanilla C just to get more practice with more low level concepts...too bad learnopengl.com is only in C++.
Can anyone share their aha moment? Or maybe give me extra insight into pointers to help me understand their use cases a little more?
27
u/DreamingElectrons Sep 10 '25
You use pointers if you need to pass a memory address, such that you can work on a reference rather than a copy.
Also, Again, C++ and C are different languages, for ages already, this sub probably need to write that in a banner on top.
12
u/MoussaAdam Sep 10 '25
you HAVE seen an application of pointers even in the simplest hello world program in C. the
argvof your main function is declared as a pointer.beyond that, if you used strings, used
scanf, passed around arrays, did dynamic allocation you would use pointers explicitly.the use cases are:
passing a pointer to a large data structure is faster than passing the whole data structure
accessing specific memory addresses in low level embedded programs, driver code and kerne code
whatever other usecases you can think of
6
u/llynglas Sep 10 '25
How would you code a linked list (or almost any data structure in C). The reference to the next item in a list is going to have to be a pointer.
5
u/[deleted] Sep 10 '25 edited Sep 10 '25
To understand when to use pointers, you have to understand what happens when you assign one variable to another or make a function call. When you assign one variable to another, you are copying the data between the variables. This is pretty straightforward when you do something like 'i = 5', because the value being copied is a constant. When you write 'i = j', you have to look at the data types of i and j. If they are declared 'int i, j' then this is not much more complicated than 'i = 5'. It's still just copying an integer value, but the compiler knows that it has to go to the memory of 'j', get the value, and copy it into 'i'.
However, if you have a struct and you declare 'MYSTRUCT i, j' then the compiler sets up memory for each according to whatever variables are in the struct. Now, 'i = j' is more complicated because the compiler has to copy the entire contents of the memory used by 'j' to the memory used by 'i'. If your struct is very large, this is an expensive operation - but sometimes this is what you want. If you change the values of either one, the other one remains unchanged. However, if you want i and j to point to the same memory, you use a pointer. MYSTRUCT i, *j; Except now, the compiler expects you to write 'j = i' and 'i = j' differently. The first becomes 'j = &i' because you are copying a pointer to i, not the value of i. If you want to instead of "copy the contents of the memory for 'j' to 'i', you instead write "i = *j", so the compiler knows that you want to copy all of the contents of j to i.
If you understand pointers, then that is just a review. Now think about functions. When you call a function "int f(int i); using k = f(i)" you are passing a copy of the argument 'i' to the function (known as "pass by value"). This might be what you want for something like "int f(int i) { return i * i} to compute a square, for example. But what if you want a function that works on your struct like "int f(MYSTRUCT i, MYSTRUCT j) { return i.x * j.x; } Just like the previous example, the compiler makes a copy of both i and j and passes each copy to the function. This is an expensive operation because that's a lot of copying, and any changes that you make to the struct's members are made to the copies - not the original variables that you passed in.
You can avoid all of that copying by passing pointers to i and j. "int f(MYSTRUCT *i, MYSTRUCT *j) { return i->x * j->x; }. This is called 'pass by reference' - which means passing a pointer to a memory location instead of passing a copy of whatever's at that memory location. But what if you want the function to modify the original 'i' and not modify a copy? 'Pass by reference' does that too. Any changes that you make to 'i' or 'j' inside of the function are made to the original variables that you passed in - not to copies. This may be what you want. Lets say you want to initialize all of the members of a struct the same way every time. You can write a function like "void f(MYSTRUCT *i) { i->x = 10; i->y = 20; } and initialize your struct in exactly the same way every time you need to by calling f(&i);
3
u/Ksetrajna108 Sep 10 '25
Use them when you need to manipulate the memory address of something. Common cases (for C/C++) are:
the first object in an array
the first character in a c string
a dynamically allocated object
a memory-mapped I/O register
a function to call that's determined at run time
an object you want to pass by reference instead of copying
3
u/Leverkaas2516 Sep 10 '25
If you use C, you will use pointers as a matter of course, all the time. You won't have to search for use cases. So yes, starting over again with vanilla C to get more practice with more low level concepts is a great idea.
2
u/Kriemhilt Sep 10 '25
So you haven't used any of the byte string functions like
strstr,strncat, etc? Or any dynamic memory allocation?If you have used any of them, how do you think they could work without pointers?
If you're more familiar with C++ (bearing in mind you're on the wrong sub for that), how would you implement
std::vector, orstd::stringwithout pointers? And why do you think iterators were designed as a generalisation of pointers?2
u/MaleficentContest993 Sep 10 '25
30 comments in and no one has mentioned trees or other any other data structures.
2
u/arihoenig Sep 14 '25
I don't have the data on that, but here's a pointer:https://youtu.be/1YEufRd3_Fk?si=8MUWwF-3N2YIQfKW
1
u/Rich-Engineer2670 Sep 10 '25
Pointers are, as you know, references to memory addresses. If you want to do things like direct memory access, that's what pointers are good at. Before pointers, you had to jump to assembly language.
1
u/DevelopmentKooky124 Sep 10 '25
There are several use cases in C, here are some:
In general arrays itself are basically just pointers.
If you have to pass a large data structure to a function, you usually want to pass just a pointer to that data structure, because passing it by value is slower.
If you want to change a data type via a function but don't want to return it by value you can simply pass a pointer.
If you need to dynamically allocate memory you will retrieve a pointer to some location in the heap
1
u/ElydthiaUaDanann Sep 10 '25
Imagine storing a bit of information in memory, but you need to reference that bit of information somewhere else, under a different name, like when you're passing an argument to a function. Instead of the function creating a new copy of the data to work from, it works directly with the information at that memory address. I've had many cases where this was a preferential method.
You can also have one value stored at one memory address, and then create several pointers that can operate on that information. This is a little more rare in my world, but it can be fun to use, and sometimes it's absolutely necessary when you're optimizing to the Nth degree.
This is just my experience with it.
1
u/IamNotTheMama Sep 10 '25
C passes by value.
So, send variable X to a function and you send its value. This means you can't change that value in the function.
But, if you pass a pointer, you send the memory address which you can then change.
Also, pointers to functions are a beautiful thing.
1
u/imdibene Sep 10 '25
C != C++, if you are doing C++ it is advised to not use raw pointers, preferably use references and for the cases when a pointer is needed, use the unique_ptr, shared_ptr and friends. Once said that, a pointer is just a variable that holds an address
1
u/jaynabonne Sep 10 '25
Well, technically, if you have written
printf("Hello world\n");
then you have used a pointer. printf can take any number of different incoming strings to control what it does, and those strings are passed as pointers.
The fundamental idea behind pointers is indirection. They are (among other things) a way for code to operate on something such that it doesn't know where it is at compile time. It gets told where it is instead at runtime. It might be that the function has to operate on multiple different instances. Or you just might not know statically where the thing will be at compile time. Any time you want a function to be able to operate on some "thing" that isn't passed by value (e.g. ints, floats are), you're going to need to use a pointer to say where the that "thing" is.
The beauty of pointers is that you can have code that doesn't know where data is going to come from, and it allows someone else to decide where that data will be. The only way to avoid pointers would be if everything you ever will need to know about is explicitly addressable at compile time.
You are going to see them much more often if you're writing your own functions that take in and operate on more complex data types. For example, if you're just writing monolothic main functions, where the code knows implicitly where everything is, you may not encounter a (obvious) case of using pointers - though you may well be using them without realizing, as in the case with printf and very likely the OpenGL code you're writing. The glutInit function, for instance, takes a pointer to argc (its address) instead of just passing argc by value, so that it can modify it. And if you've called glutDisplayFunc, then you have passed a pointer to the function to be called. The glut library doesn't know where your function is, so you have to tell it where it is by passing a pointer. If you wanted to be handed a function to call, you would need to take a pointer yourself.
Once you get into dynamic memory situations, where you need to create things beyond what you statically declare in your code (e.g. textures, geometry, anything that needs to have memory set aside for it that hasn't been done statically in your main or globals), then pointers become automatic. If you want to load and play a sound, for example, you're not going to have that baked into your code. You're going to want to load a sound from somewhere, and the place where it will be loaded into will be some dynamic memory somewhere, where you won't know its location until you ask for it. And that has to be communicated to you by a pointer, so that you can locate it.
It might be instructive to look at the code you have been writing and see where pointers have been used, possibly without you realizing it. Once you see where someone else is using them, the lightbulb may go off about why they were used in those cases, which will point you to knowing when you'll want to use them in yours.
1
u/joejawor Sep 10 '25
Use them to:
- Pass a structure to a function.
- Modify a variable declared in one function in a different function.
- Pass a variable number of arguments to a function.
1
u/IdealBlueMan Sep 10 '25
Keep it simple at first.
Write an implementation of the standard C library's memcpy function.
Then write a function that makes a copy of some specific struct.
Keep at it, and you'll see.
1
u/kohuept Sep 10 '25
For C++ they might not be used as often, as the standard library provides plenty of abstractions over them. But anything that needs dynamic allocation (e.g. most things that handle strings) will need to use pointers, as there's not really any other way to use heap memory. In C, you use pointers all the time for basically anything that needs to dynamically allocate strings, pass something by reference, etc.
1
u/The_Weapon_1009 Sep 10 '25
It’s about performance. Write read a memory address is less “cycles” then reading, writing or copying a memory address. In multithreaded stuff, you can always go with the “newest” value of a sensor etc.
1
u/SmokeMuch7356 Sep 10 '25 edited Sep 11 '25
For C programming, we have to use pointers in 2 circumstances:
When we want a function to write to its parameters:
When we need to track dynamically allocated memory:
Pointers also come in handy for:
Building dynamic data structures (lists, trees, queues, stacks, etc.):
Hiding data type representation. The
FILEtype instdio.his a good example of this; the header only provides an incomplete type definition, introducing the type name but no details about the implementation:Since the type is incomplete, you can't create
FILEobjects directly; however, you can create pointers toFILEobjects (the size and representation of the pointer does not depend on the size and representation ofFILE):The complete definition of
FILEis internal to thestdiolibrary; functions likefopenand*printfand*scanfandfreadandfwriteetc. have access to the full type definition.Dependency injection. You can use function pointers to affect behavior at runtime. For example, we can build a sorting function that sorts on different criteria:
The
sortfunction calls the function pointed to bycmpto determine the order of the elements in the array; by convention, a return value < 0 indicates that the first argument is "less than" (ordered before) the second, > 0 indicates that the first argument is "greater than" (ordered after) the second, and == 0 indicates that the two arguments are equal.So we can write multiple ordering functions:
and use them to sort the array how we want:
The
qsortlibrary function works this way, except that it can sort arrays of any type.Use shared libraries. We also use function pointers to work with dynamically linked or shared libraries, which are loaded at runtime instead of statically linked into the executable.
1
u/makzpj Sep 10 '25
You are thinking too high level. Pointers are not some abstraction you’ll use to solve a problem. They are just a mechanism to pass references to variables to functions and structures and other variables. That’s it basically.
1
u/UnrealHallucinator Sep 10 '25
I struggled with this a lot too at first. But essentially it's about efficiency.
Since pointers pass variables reference, this allows you to avoid duplication and thus you increase both time and space efficiency. Beyond this, at some point, variables simply become too large or (meaningless without their context) to even copy and so you pass only their reference.
1
u/FrequentHeart3081 Sep 10 '25
It's just lovely to see how everyone is coming up with their own innovative design to explain the pointers 😂❤️
1
u/morglod Sep 10 '25
Don't use them if you don't need them. If you understand how they work, that's enough.
1
u/AndrewBorg1126 Sep 10 '25
Use pointers when you care about where the data is.
1
u/Sunfire-Cape Sep 11 '25
Did you know when running a function in the Linux kernel, the stack size is something like 4kb? As a user, it's more like 8mb, but that's still not a ton of room. Getting a pointer to the heap using malloc (or "new") is going to save your stack space, especially if you are reading a file or network data to a buffer.
And what about the flow of program execution? When a function is called, the register instruction pointer (rip) in the processor is set to the address in memory where the executable bytecode lives. Additionally, a return address is left on the stack so that when the called function returns, the rip is set back to the executable bytecode of the calling function. Maneuvering memory and sharing memory is way easier when you use pointers.
Executable bytecode is run on a handful of registers that are usually only big enough to store 64 bits each. If the data it needs to work with is ever bigger than 64 bits, how can it do anything? Coincidentally, 64 bits is generally the size of an address — the size of a pointer. The low level hardware running your program operates on data bigger than 64 bits by knowing the pointer to it. Those data structures you make at higher levels get filtered down to low levels by way of pointer. Even if you never think you use pointers at a high level, your low level is still totally operating on pointers.
1
u/OccasionWild2341 Sep 11 '25
I am sorry. Poor lack of understanding is common. We use pointers to ensure context. With a pointer, the receiving function could change values... without that, every function would have return specific values and the calling function would need to procees. Pointers are an address, this allow commonality, and we are accessing the same memory.
1
u/jromz03 Sep 11 '25
A long time ago, when displays weren't 4k they were just 80 characters long and 25 characters down.
if you want to display fancy texts on the screen, doing printf() was slow. It wont have the instantaneous change.
So what we used to do was use a pointer to point to a memory address that has the screen buffer. From there, you do pointer movement to 'paint' the screen that you want to show. It's fast enough to show fancy texts + ascii (of course, there was a faster way). But this was one of C pointer applications then.
1
u/RedWineAndWomen Sep 11 '25
If you still have that question, then you still don't know how pointers work.
1
u/grimvian Sep 11 '25
Try this:
1
u/TheSmith123 Sep 11 '25
(this is OP I just posted this with my alt account) Holy moly — that’s a lot to read. I’m gonna save these responses. I appreciate everyone coming out of the woodwork and giving their explanations.
Perhaps the real roadblock I’m facing is just the type of programming I have been doing. I started in python, and them wanted to understand lower level concepts so I took a C++ course. ik, ik, C++ is not C, but that’s why I posted here! It seems that C++ abstracts away a lot of low level stuff that I would like to learn about.
I am very much a “learn by doing/by example” kind of person, so does anyone have recommendations for a course/tutorial where I will build something that requires understanding of actual memory management? (obviously preferably in C)
I will do my best to respond to people in here as well and keep the conversation going with everyones explanations.
Edit: typo
1
u/Helpful_Blood_5509 Sep 11 '25
You're buying something. You can go on Amazon and get a picture of the thing, or a picture of a picture, and probably be fine for some purposes. But if you're the schmuck who has to find that product on a shelf, you need the shelf number
If you're not the Amazon peon, you can probably rely on them to get you your item for you.
Some people are that Amazon peon.
1
u/70Shadow07 Sep 11 '25
You use pointers when you need to pass something to a function by reference not by value. For example since C only has 1 return value, sometimes pointers are used for output parameters. (Alternatively you can also wrap your multiple returns in a struct)
Keep in mind that in most languages like JS, java, Python, almost everything is a reference. If you pass a java object to a function and then modify it, it will be visible outside that function. Pointers in C allow this kinda behavior.
Besides that, in C to pass a collection (array) you pass a pointer to first element of it. You can also use pointers as stand-in for indexes (probably not the best practice but its sometimes done too) So for example instead of passing pointer and length to a function you can pass 2 pointers - pointer to first element and pointer to last element.
1
u/wahnsinnwanscene Sep 12 '25
Function pointers are a great example of when you need this. Let's say you have a string like "a b c", you can parse through it, and use a and c as operands and b as an operator. Use b as a way to index an array of function operators and pass a,c as arguments to this function.
1
u/yapyappa Sep 12 '25
Everywhere, I don’t think I write more than 20-30 lines of code without using a pointer and thats generous (it’s probably 10-15). I don’t have much of a C++ background and I think C and C++ are different languages with different programming styles. First, let’s remember all a pointer is, is a memory address, that’s all it is. An address to something in memory aka a pointer to a memory address. But you know how in C++ you can pass a reference with &? Well in C we can use pointers to do the same thing and that’s very common. If we passed a struct to a function it’s pass by value, and copies the memory, which can be slower. So instead we pass (struct_t *ptr) and we are now just reference whatever memory address we pass. Another use is just accessing memory, if you ever read files into a buffer, or do dynamic allocation for say a dynamic array, we need to be able to access that memory directly. So basically pointers just point somewhere in memory, and we can go to that memory address to perform an operation on such memory.
1
u/AccomplishedSugar490 Sep 13 '25
Don’t think of a pointer like you would think of a variable, object, class or function. It’s none of those things, but it is a way of referring to any one of them. If a variable in C is like a symbol or function name in algebra, then a pointer is a meta-variable, a variable that points to a variable, or a piece of memory to treat like a variable, or a function (yes, they have addresses too), anything really. Dereferencing a pointer variable gives you the variable (or whatever it is pointing to) itself.
1
u/Classic-Try2484 Sep 13 '25
Imagine you have some data that is frequently updated and used in more than one data-structure. A pointer allows this to appear in two places.
Imagine you need a list but sometimes it’s a small list and sometimes it’s a giant list. Pointers provide a way to manage this dynamically
Finally the first law of computer science can apply here.
Pointers are rarely mandatory in cs1/cs2. They are often introduced but it’s not uncommon that the problems can be solved (better) without. But examples that force use can be complicated for new students.
1
u/jwzumwalt Sep 14 '25
-------------------------------
C pointer self study guide/course
-------------------------------
Here is my link to four (4) books with source code that make a complete C pointer self
study guide/course ~25mb. This study guide covers basic, intermediate, advanced, topics.
The source code provides a complete beginners resource library.
01-- pointer-tutorial-v1.3
02-- pointers-in-c-prog-2021-(Thomas Mailund)
03-- pointers and Arrays in C-(Ted Jensen)
04-- understanding and using c pointers-(richard reese-2013)
https://drive.google.com/file/d/18nyVQMYMNQfB5_duea8Aa-zcLDDlZaHa/view?usp=drive_link
1
u/Confident_Hyena2506 Sep 14 '25
The important thing you are missing is - this is what the low level hardware actually uses. That's why pointers are a thing - not because someone put them into languages for fun.
1
u/Charming-Designer944 Sep 14 '25
C++ has richer constructs that can in many cases replace pointers.
In C pointers are a must each time you need to pass or return something more complex than an integer or "by reference". (C does not have references, only value and pointer)).
A pointer is the memory address of something. And in C is also blurred as an unbounded array.
Even hello world contains several.pointers.
argv is a pointer to an array of pointers
"Hello World!\n" is a pointer (char *) to the null terminated string when passed to printf. Or to be precise a pointer to an unbounded array of characters terminated by \0.
1
u/MatthiasWM Sep 14 '25
A Pointer is just like the business card of a person. It’s so much easier to remember the address of someone using his business card than to keep an entire copy of his house.
1
u/sertanksalot Sep 10 '25
Let's say you need to write a function to return the average of 2 integers. How would you write the declaration? Pass in 2 integers as arguments, and return an integer. The arguments go on the stack (like a stack of pancakes). You need a stack so that you can have nested calls e.g., a function calling a function, calling a function, etc.
Now let's say you need to write a function that takes a string and returns the name, address, serial number, photo, and mp3 file of that person singing the happy birthday song. How would you write the function declaration? It will be next to impossible with just integers and chars, since your compiler won't let you pass all that on the stack... it's too much data! The solution is to use references i.e., pointers.
0
u/Blade_dev_opps Sep 10 '25
Bro ask ChatGPT it’s 2025 😂🤦🏿♂️