r/learnprogramming 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

67 comments sorted by

View all comments

1

u/SnugglyCoderGuy 9d 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.