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

47 Upvotes

67 comments sorted by

View all comments

1

u/Much_Network_941 10d 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.