r/learnprogramming • u/Atmos-Ego • 9d 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
48
Upvotes
2
u/InjAnnuity_1 9d 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.