What's the point of pointers (C++)

Hey everyone, I'm in second level C++ and am learning pointers, and understand the use of the stack and the heap and dereference operators and stuff like that. But what I don't understand is why does implementing it this way improve your code? It just seems like something that'll lead to a logic error/memory leak. Thanks!

By @allballs on Wed 26 Apr 2017 |
Tags c++ pointers

Responses:

Offer your help. Be nice!

@msjcat
0

I am not 100% familiar with C++, but I am with C, and a quick Google search tells me that they are identical other than a smart pointer. So this answer may be slightly off, but hopefully it answers your question.

Normally when you call a function that takes variables you are only passing the value. The program has to make space in the memory for the new variable with the given value. Then, if you want to update that variable's value, you have to return the modified value and overwrite the old variable.

With pointers you assign a pointer to the address of the variable, which is the original variable. This not only means that the program does not have to create more space in memory, but any modification you make to the pointer affects the original value, because it is pointing to it. So if you want to modify a variable's value, you do not have to return a value and then assign it, since you are working directly with the original variable.

As @msjcat mentioned, the core idea is that you are able to pass around the address of a variable, rather than the value of a variable. To make this clear, I'll quickly explain the difference between passing a variable "by value" or "by reference."

Think about this: you need to move around an array containing thousands of objects. If you didn't use pointers, you would be creating a new copy of your array every time you sent it as an argument to a function -- this is called passing a variable "by value". That would be very, very slow, considering we'd have to copy thousands of objects in our case.

On the other hand, if you sent your array "by reference", that would mean that each time you sent the array as an argument to a function, the function would not copy the whole array. It would, instead, copy the array's memory address, which is usually just an integer.

What would you rather copy: a single integer, or thousands of objects?

Pointers give you the power to choose how to move your variables around memory: by value, or by reference. This was a short and simplified answer, and there are other benefits to pointers as well -- you will see them soon enough.

Login to leave a response!