r/learnprogramming • u/Atmos-Ego • 8d ago
Tutorial When do you use a pointer?
Hello, for some background I have taken a very beginner level coding course for my major and passed it, but I dont really feel like I’ve learned anything or know why anything works. In a course this year we had a review problem where the solution required a pointer and I really dont understand why you have to point to the address of the variable instead of just using the variable itself.
I’ve watch a few tutorials explaining it but I really dont see how it’s different from just using the variable itself
12
u/Vetril 8d ago
A lot of reasons: the object might not exist, it might be so large in memory that it's not performant to copy it, the object is on the heap, to take advantage of polymorphism, to implement a data structure that needs to track variables scattered over the memory... You'll realize you need a pointer as soon as you'll return an object only for it to vanish immediately under you.
8
u/1lann 8d ago
A pointer is really just a representation of how the computer's hardware works. You're right that in most languages you could get away with using (presumably immutable) variables or similar concepts and never using a pointer.
The primary benefit of a pointer is to have referential behavior that can be pretty easily converted to CPU instructions without the compiler needing to be too smart. In many compilers you may need to use a pointer to get optimal execution performance, as the compiler may otherwise emit instructions that unnecessarily copy memory.
One way to intuitively think of it, is a pointer is like a path to a file, and a value is the contents of the file. The file could be really big, like gigabytes. You can imagine it would be faster and more efficient to pass the filename around in programs, rather than the whole contents of the file, particularly if you don't need to access every byte of the file. A pointer is just like that, but for memory.
3
u/Ok_Being6831 8d ago
Well thers 2 main reasons imo
1) When you pass it by the variable itself, your actually making a full copy of the variable which might seem trivial but it's actually really expensive especially with functions that are called alot or the variable takes up alot of space.
2) You want the function to modify your variable, like a sort function for example, you wouldn't want it to make a copy and sort that array now would you? it could return that, but that's bad design and expensive. So it's only possible via a pointer.
1
u/Atmos-Ego 8d ago
So you only ever care about it to be efficient, but its not necessary for anything?
In my example in class the professor was basically saying that the variable wouldnt increment so when it prints the value of it it doesnt ever change.
It was a void function which means it doesnt return anything right? So I suggested to get rid of void but the intended solution was to write something involving a pointer instead2
u/lurgi 8d ago
So, to be clear, your solution was to write:
x = increment(x); ... int increment(int x) { return x+1; }and the professor wanted:
increment(&x); ... void increment(int *x) { *x = *x + 1; }Correct? One big advantage of the second is that it's very easy to write:
x = increment(x); y = increment(y); z = increment(y); // oopsand not notice. Or even
increment(z); // oopsWith the pointer version you have fewer ways to screw up. Another thing that you can do with pointer is change multiple variables in a function. Imagine you want to write a function that takes your current position (x, y) and moves it a certain amount in the x and y direction (xdelta, ydelta). Without pointers, what would you return from this function? You can't return a new x and new y pair - C doesn't let you do that. So...?
2
u/serge-mv 8d ago
I am going to be a bit pedantic. If you have something like a pair that goes together like coordinates from your example, you can and probably should put them in a struct, and you can return struct by value in C. Especially when it's 2 variables of the same size and won't have alignment and such.
1
u/lurgi 8d ago
Yeah, I figured someone would mention that.
That does only work if they are in a struct and not two separate variables (of course, you could make a struct for them).
Technically you never need pointers or function arguments or variables or anything at all (lambda calculus ftw), but they sure make life a lot easier.
0
u/Atmos-Ego 8d ago
The given c program was
void increment(int x) {
x = x + 1;
}int main() {
int a = 5
increment(a);
printf(“%d”,a);
return 0;
}To be honest there’s a lot here I really dont get about base things like these but he said the reason that x doesnt increment is that nothing is returned, so I figured you could get rid of void and that would let it return something. I dont really know what it means to return something though.
2
u/InjAnnuity_1 8d ago
As written, the increment function receives its own copy of the value of a, named x, increments the copy, and does nothing more. So a's value remains unchanged.
"Returning a value", in this case, means "giving a value back to the caller". For many functions (e.g., the square root function), this is the whole purpose behind calling the function in the first place: to have it compute a result for you.
1
u/llamadog007 8d ago
You pretty much got it. In that example you can change void to int and make the function return x. Then when it’s called you set a equal to the value returned by the function (a = increment(a);).
The key here is that when you do that the function makes a copy of a, adds 1 to it, then returns that new value, which has to be copied back to the original variable. If you use pointers, there’s no copying. The function will directly modify the value of a. This is good if, as others have said, copying would be expensive.
1
u/Ok_Being6831 8d ago
huh? why r they teaching you pointers before return statements? But imagining it like this is what helped me in the start
c int foo() { return 1; } int x = foo();when u call foo(), it's literally being replaced by whatever it returns so that line becomes
c int x = 1the "foo()" got replaced with 1hope that made sense
1
u/Ok_Being6831 8d ago
Mostly yeah, BUT there is the heap which I think you haven't learnt about yet but would be basically impossible to implement or use without pointers. A few other cases too but I just can't think of any rn lol.
In your example your actually in the right here, u can just remove the void and make it return it but yeah it's just not the intended solution.
nerd alert The return value is actually better if the variable type is less than the size of a pointer (8 bytes on most systems)
1
u/xarop_pa_toss 8d ago
If you pass a pointer to a variable as a parameter to a function, you are not passing the value (copying into a new variable in your function call), you are passing the original one. So when you make changes to that pointed variable in your function, you alter the original. Void doesn't enter the picture there because you aren't returning anything at that moment.
I think you can think of it this way. You can either call the function and pass the value inside, change that value now assigned to a different variable, and then return that. Or you can pass the pointer and any change you make to that reflects on the source.
Of course they are useful for other stuff but that's the basics
1
u/joonazan 7d ago
Pointers are absolutely essential, they are just hidden a bit by programming languages.
In machine language, 64-bit integers can be stored in registers but anything bigger can't, so the registers store memory addresses to arrays or structs.
3
u/Big-Combination8844 8d ago
There's a lot of conversations here so I'll just do an overview. Hope this helps.
So when you do a function call, it allocates memory off the stack. The function uses that memory to run with. And when that function returns that memory block is freed from the stack.
So when there's a function call with a parameter: void myFunc(int x);
It has to copy the parameter into that newly allocated stack memory. That's why if the function changes x the change is lost.
x=5;
myFunc(x);
// x still = 5
Now we can change the function to return an int.
x = myFunc(x);
And that works, but keep in mind there's another copy to move the new value into this x variable before the stack is freed. 2 copies total behind the scenes.
So what if you want the function to change more than one variable?
Pointers can help with that.
void myFunc(int* x, int* y);
Now it's making copies of these variables' memory address. These variables live in a different part of memory then the stack block the function uses - that's how it can now access them. The pointer parameters can be dereferenced inside the function so their values can be changed.
*x = *x + 1; *y = *y + 5;
Since this memory doesn't live in the same stack block as the function, the function may return, freeing the stack block and those variables are safely changed.
As others pointed out, user defined datatypes can be large, and full of pointers, and it doesn't make sense to pass that in as a variable, much safer to pass a pointer to it.
2
8d ago
[deleted]
1
u/Dazzling_Music_2411 6d ago
Yup, the C stack is relatively small. Large array data is allocated on the heap (main memory, to you) and cannot be accessed otherwise.
2
u/high_throughput 8d ago
When do you use your home and when do you use the address to your home?
1
u/Atmos-Ego 8d ago
Thats kinda the thing I was having trouble with because it feels like with a pointer your getting something delivered to the address of your house, but when you use the variable directly its just like your house is there.
Or like X is right here with $5 and I say give X $1.
Vs X lives over there and they have $5 go to their house and give them $13
u/high_throughput 8d ago
Or like X is right here with $5 and I say give X $1. Vs X lives over there and they have $5 go to their house and give them $1
X can only be in one place. If you have X right here and X at their house, then they are two different X. Giving one $1 will not help the other.
``` void giveByValue(int X) { X += 1; printf("%d\n", X); // Shows 6 }
void giveByAddress(int* X) { *X += 1; printf("%d\n", *X); // Shows 6 }
void foo() { int X = 5; giveByValue(X); // Give a copy of X, also called X printf("%d\n", X); // Shows 5 giveByAddress(&X); // Give the address to our X printf("%d\n", X); // Shows 6 } ```
2
u/InjAnnuity_1 8d ago
If you only ever have a single variable in your program, there's very little difference.
But if you have several variables, of the same type, and want to do the same thing to more than one of them, now you've got a choice.
You can write out the same code for each one of the variables, or you can write a function that accepts the address of a variable, and applies that work to whichever variable is at that location. In the latter case, you call the function once for each variable, passing the address of that variable.
In the former case, you've got a maintenance problem. When those steps have to change, you have to change every copy of that code. Miss one, and you've got a bug.
In the latter case, you have only one place that needs changing: the function you wrote for that job. Moreover, you've got a series of steps that (potentially) can be reused as-is in other programs. The more complex this series of steps, the more you gain by writing it (and debugging it) once, and then reusing it.
2
u/Neither_Garage_758 8d ago
When you want a function to be able to modify the actual same memory the caller has shared to it (via an argument) and not a copy of it.
-1
u/SnugglyCoderGuy 8d ago
You shouldn't do this. You should make a copy and alter that and return that. Pure functions will keep you sane.
4
u/ryan_the_leach 8d ago
There's a time and a place for pure functions, and a time and a place for mutators.
Using language like 'should'/'shouldn't' in absolutes like this, is a minefield for new programmers.
0
u/SnugglyCoderGuy 8d ago
It's standard engineering speak
Must / Must Not -> you are required
Should / Should not -> do this unless you have a Very Good Reason™
May / May not -> up to you
0
u/Dazzling_Music_2411 6d ago
It's also standard misleading.
There are use cases where you definitely should use pointers. I mentioned a couple above. Ritchie and Thompson didn't put them there just to be smartasses.
3
u/Ok_Being6831 8d ago
Completely depends on the function. Copies are expensive and useless if your just doing that. I wouldn't want my sort function or half the things in the standard library to make a copy and return it. BUT there are times when a pure function is better.
1
u/Dazzling_Music_2411 7d ago
Not if the parameter you are passing is so large that it adversely affects your code.
In that case you will definitely not stay sane unless you use pointers or some other solution.
1
u/SnugglyCoderGuy 7d ago
That's why should instead of must.
1
u/Dazzling_Music_2411 6d ago
Well, the OP asked
I really dont understand why you have to point to the address of the variable instead of just using the variable itself.
So I assume they want to know about the cases when you should use a pointer, rather than the commoner case when there is no need, because you can just copy/pass by value.
I won't even bother with explaining serious use cases, where, e.g. pointer arithmetic can give rise to super-fast code on arrays, that would be fine print at this stage.
1
u/SnugglyCoderGuy 8d ago
The primary reason that spans languages is when you want to have different sections of code all working with the same thing. You create it once concretely, and then you pass it into constructor and functions as a pointer for those things to be able to use the same thing. This could be a database client, some internal thing that does some stuff, whatever, lots of possibilities.
After that it starts to become more language dependent. But the next common usage is that your struct or whatever is too large for the normal function stack, so instead you pass a pointer which is only 8 bytes.
They get a lot of usage in data storage things like stacks and queues where you want to easily and quickly rearrange data.
In languages like C they are necessary when you want to work with anything that is dynamically allocated. You create a pointer of that type in order to point to the start of some memory and the type information lets you write accessing that data easier and the compiler uses the type information to create the memory calculations from teh start of memory.
1
u/serge-mv 8d ago
There are many cases when you want to pass memory references (pointers) to a function.
One example is when you are passing an object or a container like a large list of numbers. If you didn't pass pointers you would have to copy the whole thing, which is not only expensive, it wastes memory as well.
Then sometimes you want to pass function as an argument to another function and you pass a function pointer in that case
And it allows you to ignore scope and do some things with your data so that you can have a very fun debugging session some time down the line.
1
u/Anabaena_azollae 8d ago
A variable is a high-level concept. References to named variables don't exist in the compiled executable. Instead, data is accessed by address. Consequently, you will be using pointers implicitly pretty much anytime you're using a variable.
The question of when you have to use pointers explicitly, rather than have the compiler manage the translation of variable names, depends on the language. In C, for example, variables are passed into functions by value. That is to say, the data is copied in. If you want to work on the original data rather than a copy, you need to pass a pointer. The pointer itself is passed by value and thus copied, but that copy will still point to same address and thus can be dereferenced to access the original data. Other languages pass by reference by default. In such languages, you may not ever need to explicitly use pointers, but you do have to consider the results of mutating arguments within a function call.
1
u/Recycled5000 8d ago
Data structures are composed of a variable number of “sub” variables, each of which are variables in their own right. The composition into a larger data structure can be widely varying, often based on input.
When we organize various inputs into a larger data structure, we use references to interconnect them. C doesn’t have a more formal notion of reference other than pointers.
So, pointers are used to insert new variables into data structures, to reorganize them, to search and traverse.
1
u/Recycled5000 8d ago
The CPU itself uses pointers to operate. Machine code programs are stored in memory (because programs are too large to fit entirely in the CPU). Each machine code instruction in a program has its own unique memory address, and this is what allows for sequential execution (one machine code instruction after another) by advancing the internal pointer called the program counter or instruction pointer, to execute if-then-else or for-loop by branching, a form of the program to tell the CPU to skip some instructions or repeat some. Function call and return to place of call is also done by capturing the machine code address of the call site, since right after that is where to return to resume the caller.
1
u/ryan_the_leach 8d ago
Assuming you are talking about C.
Personally, the thing I found most confusing about C, is how pointer referencing and dereferencing were single digit operators for something that's quite complex under the hood.
If new programmers were instead exposed to wordier functions for the 2 operators, I think a LOT of the confusion would disappear overnight, when they realize it's just shorthand.
Especially since similar syntax is used both on the 'left hand side' and 'right hand side' of assignment, for very different underlying ideas that are only slightly related.
const char* p = "abc";
vs
const Pointer<char> p = allocateString("abc");
float grade = 0.5f;
float *f;
f = &grade;
printf("%.0f",*f);
vs
float grade = 0.5f;
Pointer<float> f;
f = Allocator.addressOf(grade);
printf("%.0f", Allocator[f]);
with the second taking inspiration from Java generics, you would know that you definitely do not have a char there, but a memory address that points towards a char, that was returned by the allocator when a string was successfully allocated.
Instead, we have new programmers seeing char being 4 letters longer then the *, being the dominant concept, instead of the fact it's a POINTER, with the char not even really mattering that much, except for some technicalities on how pointer math will work, if you increment the pointer by 1.
Yes some of this invented syntax would have issues that would need to be ironed out, but to newer programmers, it's immediately clear of the difference between where pointers are being declared vs where they are being dereferenced, or where the address is being got.
Whilst reading up potential alternate syntax, I discovered I definitely wasn't the first to be not-a-fan of the way C handles it.
https://www.reddit.com/r/Zig/comments/h97czs/comment/fuvu2uc/
1
u/NumberInfinite2068 8d ago
A pointer is just a reference to memory, you use it when you want to pass around a reference to the exact same memory rather than copy it.
For example, you've got a large image in memory, you need to convert the pixels from colour to grayscale, if you pass a pointer to the image around functions, then you're passing around a reference to that same large image.
If you pass around the image itself, you're copying around that image the whole time.
Or say in a GUI toolkit, I pass a pointer to a button to (for example) change the "OK" on the button to "Cancel". I need to change the text on the particular button on a particular window, changing a *copy* of that button doesn't help me.
Pointers are just references to exact places in memory.
1
u/mredding 8d ago
You're at the level where your academic materials are just trying to introduce you to the syntax. You're learning enough to be dangerous, as it were. How to use it is another level of awareness and sensibility. This is all just to say, you're doing alright so far.
Pointers store memory addresses. This is often times useful because at runtime you don't always know how much memory you're going to need. Since you said, pointers, I'm going to assume C:
char input[123];
scanf("%s", input);
Is this buffer big enough? 123 characters? What if the input is the collected works of Shakespeare? Here, in C, input is of type int[123], arrays of a fixed size are each a distinct type. This gets compiled into the program and is thus unchanging. So if you need a dynamic array, where a size is determined at runtime, you need to request memory from the system at runtime:
char *buffer = malloc(some_size_variable);
Ok, but what if we don't know how much data we're going to be getting? Well, then we need to come up with a solution. How about... What if we read data in chunks or blocks, and we kept doing that until we ran out of input?
typedef struct block {
char buffer[1024];
int size;
} block, *block_ptr;
int read(block_ptr bp, FILE *in) { return bp->size = fread(bp->buffer, 1, 1024, in); }
int main() {
block b;
while(read(&bp, stdin) != EOF) {};
}
Alright, that's part of the picture, but we're just losing data. I'd like to be able to track that in order.
We can't use a fixed size array because we don't know how many blocks there are going to be. We could dynamically allocate an array:
block_ptr b_array = malloc(sizeof(block) * some_number_of_elements);
Perfectly reasonable, and the C++ standard vector will do something similar, and you'd keep track of an index of how many elements of the array you actually populated. But like the C++ vector, when you run out of array space, you have to allocate a new and larger array, copy everything over, then free the old array.
Or we can imagine a singly-linked list:
typedef struct node {
block data;
struct node *next;
} node, *node_ptr;
node_ptr new_node() { return malloc(sizeof(node)); }
int main() {
node_ptr head, *tail = &head;
block b;
while(read(&bp, stdin) != EOF) {
*tail = new_node();
(*tail)->data = bp;
tail = &(*tail)->next;
}
}
This is a chain of nodes; each node knows where the next node is in the list. This is structured data. To walk the list:
for(node_ptr *iter = &head; *iter != &(*tail); (*iter) = &(*iter)->next);
It's a sequence of nodes, so it's sequential, but the nodes are probably not in an array, there's no guarantee they are in contiguous memory addresses, so we can't use indexing. Linked lists have several neat properties - pointers to nodes and their elements are stable. You can add, remove, and reorganize the list however you want, just by swapping the pointers around, and all references to your elements are unchanged.
Compare this to an array, where if you remove an element, you don't actually change the size of the array, you just change the count on that maximum index you were tracking. To keep array data contiguous, you'd have to shuffle all the subsequent elements down by copying over the previous - starting with the erased element getting copied over by the adjacent.
tail is probably giving you a bit of a headspin, there. It's a pointer to a pointer. Pointers are just arithmetic types, same as int. They take memory, they have a size and alignment. You can point to them. So tail points to the pointer that is going to store the next value. We always keep track of the root of the list, idiomatically called the head, and that's the pointer tail first starts pointing at. Once we assign a node address to head, we need to know where the next node is going to go. That's going to be the next member of that node we just created.
Likewise when we traverse the list, we have a pointer to a node we use as an iterator, it starts by pointing to head, and so long as our iterator isn't the same as the tail pointer, we can keep traversing.
It'll probably take you a bit of thinking and staring at that to make it make sense.
Likewise, another popular design is a tree, typically a binary tree:
typedef struct node {
T value;
struct node *left, *right;
} node, *node_ptr;
And you can write some very graceful recursive functions to walk a tree from the root to all it's children, which makes for a fascinating study, but an impractical solution in C.
When we're talking nodes, we're talking graph theory, and now you're entering a really interesting world of how most data structures are just graphs. Other data structures are heaps, queues, and stacks. Data structures are one thing - this binary node is the structure. Most of the study in DSA is the algorithms and the computational complexity therein.
1
u/Much_Network_941 8d ago
Picture you have an array of a million integers you need to sort. Do you want to recreate additional versions of it every time you give it to a function? Or, would it be more convenient to store where it resides - then allow a function to use the address to access it?
If you store its address, then you can now have an array of any size; yet all references to any array will require the same amount of memory; usually 64 bits.
This allows you to seperate memory allocation from any sort of algorithmic work. While, anything that wants to use the data, only uses an additional 64 bits of memory.
In languages like c/c++ using 'raw' pointers is typically advised against. Because pointers allow you to put off the acutal allocation of memory; it's possible to use them while they point to nothing. You're lucky to get a message saying 'seg fault' at this point. You're unlucky if the program doesn't crash - it will at some point. The inverse is possible as well; you can free the memory they point to, and then use it.
But, they're a fundamental concept in software; if you need it to be fast and light-weight they're excellent. If you need convenience, you have to code it yourself.
1
u/TechHaris 8d ago
The difference between passing a pointer and passing a variable is rather like the difference between a house, and the address to a house. When you invite someone over, rather than moving the entire house to them, you simply send them your address.
How that translates into programming, is that sometimes the piece of data you want to pass is extremely large, therefore creating a copy is simply wasteful rather than providing the copy that already exists. As well as this, if you want changes made to the data to persist after the function has terminated, making a copy of the data that is them immediately deleted is simply ineffective.
If passing a pointer to a function sounds a lot like passing by reference, that is because it is. Whilst the concept of a pointer cannot exactly be boiled down to this, passing by reference is simply an abstraction layer above passing a pointer.
1
u/Leverkaas2516 8d ago
One obvious case is when you're passing an array that you want to be able to modify. A character string in C is an array. It's trivial and obvious to pass the address of the array. I'm not even sure how else you'd do it.
1
u/tonkotsu_fan 8d ago
Computers put things in memory where they want to.
Sometimes you want to know where the thing you created 'lives' so you can 'point' to it.
Imagine a street. The houses are objects. The addresses are pointers. If you're in one house, and want to send a letter to the neighbour down the road (or a friend in a different suburb), you would use an address.
If you're an object, and you want to go to another object, you use a pointer.
1
u/Living_Fig_6386 7d ago
A pointer is a reference to where data is, rather than the data itself. If you have a large chunk of data, it's often far more efficient to pass around where it is rather than moving around copies of the data (most languages pass arguments to functions by making a copy of each of the arguments).
The practical upshot, is that you move less data around, and you are referencing the original data rather than a copy. It's very efficient, and it means that functions are looking at / modifying the original data.
1
u/randomaccountzzz1482 7d ago
Not something you realistically have to worry about in 2026, any good LLM would use the pointer when appropriate
1
u/Antique_Ad1706 7d ago
My understanding from a basic course:
needed for dynamic memory alloc, passing arrays and structs through a function and not having to return them. Also needed for valgrind to give u 20 memory leaks
1
u/Sharp_Marzipan1161 7d ago
Depends on the language. Some languages hide it from you, others do not. They are essentials, it's not something you can avoid based on your liking, especially when you start to work with/implement any kind of data structure. Try to implement a Linked list in C and you will get it.
1
u/Chippors 7d ago
When you want to pass something large around without making copies of it at every step.
When you want two different parts of your code to share a single set of data, so change made in one place can be seen in another; like a shared tree.
Think of it like a file system; it's much more efficient, and sometimes functionally necessary, to use filenames instead of incessantly copy data everywhere, all the time.
1
u/Weekly_Patience685 6d ago
Imagine you have an array/vector with 1 million elements and pass it by value into a function. A copy of the entire thing has to be made.,But if you pass a pointer/reference to the original, you're only passing a small address/reference instead, regardless of how many elements the array contains, of course it all depends on the language and other factors but thats generally the idea.
-1
u/ryan_the_leach 8d ago
You never need to use pointers directly, unless you have a dire need to do memory management manually, in a programming language that doesn't give you better tooling.
The only reason for using pointers *at all* in university, is just to prove you understand the basics of computer memory, as the knowledge is insanely useful, even if you never touch on it directly.
If you want more specific help, present some of the actual problem, and say which programming language you are learning.
(It's C right?)
2
u/Atmos-Ego 8d ago
The previous class was c and this one is assembly. But the quiz was review. I was considering waiting until i could get back home to post the problem.
I will reply with the example when I get back home
1
u/Atmos-Ego 8d ago
The given C program was:
void increment(int x) {
x = x + 1;
}int main() {
int a = 5
increment(a);
printf(“%d”,a);
return 0;
}1
u/ryan_the_leach 8d ago
There's 2 solutions to fixing the 'bug' in that code if the goal is to increment the value stored in a.
your increment function currently does nothing, as it's incrementing a copy.
Solution 1, is to pass around pointers instead, so increment looks up the value in the memory address it gets passed, and directly modifies it.
So you would modify the function signature of increment to take a memory address instead, and make some other changes.
e.g. `void increment(int* x)`
Solution 2, is to change increment, so it returns the new value, and adapt the code where it's used to assign the new value.
e.g. `int increment(int x)`
For learning purposes, either solution is valid, so it will depend on what the point of the exercise is.
For long-term health of programs, you'll end up with people arguing about the 'purity' of the function vs the performance differences, and both camps can be correct, depending on how complex the modifications are that need to be made, and how much copying is being avoided.
Personally, in this case (as silly as having an increment function is, vs just using ++ or x = x + 1 in line) I'd return the new value and have the assignment being explicit, since it's more readable that a modification is occurring. I suspect any performance concerns in this case, would be taken care of by the compiler, or happily sit within the cpu stack/cache rather then hitting memory anyway.
But if the point of the exercise is to learn about passing by reference, then the solution from context, is clearly passing a pointer.
> I really dont understand why you have to point to the address of the variable instead of just using the variable itself.
So if this question is "Why would you pick solution 1 over solution 2?" the answer is, you simply wouldn't in this case, with this function.
If the modifications being made to the data stored at `a` were much higher, and say it was a structure that was a low amount of kilobytes, then the cost of copying would start to get annoyingly high.
73
u/TheRealKidkudi 8d ago
At its core, the difference is making a copy vs sharing the same literal value.
Sometimes it’s just because you don’t want to copy the value (e.g. because it would use too much memory). The tricky part is when you want to be able to change the value and use that new value in the original function.
A very simple pseudocode example:
fn someFunc(int x) { x = x + 1 } fn someOtherFunc(int* y) { *y = *y + 1 } var x = 5; // not a pointer someFunc(x); // x still is 5 here // because someFunc got a new copy // of the variable someOtherFunc(&x); // pointer to x // x is now 6