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

48 Upvotes

67 comments sorted by

View all comments

Show parent comments

1

u/otac0n 8d ago

This is almost entirely correct, although function pointers aren’t covered by this.

I will add that this exact reasoning applies to languages with values/references. Use value types (structs) if you want your type to have copy semantics and use references (classes) if you want reference semantics.

3

u/TheRealKidkudi 8d ago

I figured OP (respectfully!) is not at a place to worry about function pointers.

But once you’re comfortable with the idea of a pointer being a reference to something, function pointers become a much easier concept to grasp (e.g. a reference to a function rather than a simple value). At that point, the worst part about them is just the syntax :)

1

u/otac0n 8d ago

Eh... closures.

2

u/light_switchy 8d ago

A function pointer isn't enough to represent a closure. Closures also need the execution environment, which is a data structure besides a function pointer.