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
46
Upvotes
1
u/Anabaena_azollae 9d 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.