r/learncpp • • May 17 '20
Have I understood pointers properly?
Hey everyone! I just started learning C++, and I want to know if I've understood pointers correctly. This is how I've understood it -
/* WHAT ARE POINTERS?
*
* in C++, functions do not have ownership of global scope varianbles
* that are passed into it as arguments. To allow the function to modify
* these variables, we use pointers - "a tool to share the memory address
* among different contexts, such as functions".
*
* so if we have a function that we want to use to make changes to an
* existing variable, without having to create/redefine a variable to
* use the function, we use pointers.
*
* assume we have a variable VAL. To access the memory address of VAL,
* we prepend the & symbol. The address is given by &VAL. To define a pointer
* that allows us to modify VAL within a function, we do
* int *p = &VAL;
*
* the variable *p is known as a pointer as it POINTS to the memory address
* of the variable VAL. Thus, any modificiations on *p will also be reflected
* on VAL.
*
*/
If this is not right, please let me know! I'd love to get a better understanding of this topic. Thank you!
0
Upvotes
View all comments
Show parent comment
1
u/victotronics May 17 '20
An appropriate use of pointers is for instance the linked list.
doesn't work because it would be infinite.
does work.
.... and now you can go read about the difference between shared and unique pointers. The above example should really use unique pointers, but I find shared pointers a lot easier to teach.
In the abstract: you use a pointer to have ownership that transcends scope. If you create a linked list, your new Nodes live longer than the scope where they are created, so you need to make a pointer that points to them.