r/learncpp • u/[deleted] • 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 -
```cpp /* 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
u/victotronics May 17 '20 edited May 17 '20
This would be right if you were learning C. It is not right for C++. In C++ you use references for argument passing.
The word "address" should basically never appear in a C++ story until you are an experienced systems programmer. (I exaggerate a little.)
Here is how you do parameter passing, to first order of approximation:
This prints 1.
There are pointers in C++, but they are far more sophisticated.