Autor: 24.11.2023
Pointers in C++
You can live without pointers. However, there are situations where their use is necessary, or at least "recommended" - especially for the sake of code efficiency. Every more advanced C++ programmer should know how to use pointers. Check out our article, which will easily introduce you to this fascinating topic.
How to define a pointer
How do we define pointers? Analyze the following example:
int *ptr;
The special symbol * (asterisk) indicates that we're dealing with a pointer. How should we understand such a definition?
The pointer ptr is a pointer to elements of type int.
Similarly, we can proceed for other types:
double *pointer;
The pointer pointer is a pointer to elements of type double.
Using pointers
Now that you know how to define pointers, it's time to understand how we can use them:
int *ptr;
int digit = 7;
Now we'll set the pointer and display information about what we managed to set:
ptr = &digit;
cout << ptr << endl;
The output will be:
0x7ffee55e589c
Do you see those strange characters? That's the address of the variable digit. It's the address of the variable in memory. The pointer ptr is capable of storing such information. We obtain the address of a variable using the special symbol &. Placing it to the left of the variable allows us to obtain its address in memory.
How to use an address
What does knowledge of the address give us? When we know a variable's address, we can control it.
Here's an example:
int *ptr;
int digit = 7;
ptr = &digit;
// display data
cout << *ptr << endl;
cout << digit << endl;
// change the value of digit
digit = 8;
cout << *ptr << endl;
cout << digit << endl;
// change the value using ptr
*ptr = 9;
cout << *ptr << endl;
cout << digit << endl;
Result of the above code:
7
7
8
8
9
9
In the above example, you can pay attention to the use of the pointer ptr. As you can see, sometimes we can use the pointer with an * (asteriks).
Regarding the variable digit, we can draw the following conclusions:
If ptr = &digit, then *ptr means exactly the same as digit. By executing *ptr in the code, we refer to the value of the variable that our pointer points to (which is digit). In our case, changing the value of the variable digit or using *ptr actually changes the variable digit because our pointer "knows" at which address the variable is located.
Summary
Using pointers comes with great responsibility. They can be an extremely useful tool, but they must be used wisely. In the above examples, it was clearly seen how pointers can manipulate variable values. Therefore, always think twice about how to use a pointer, as it's very easy to create problems for yourself. Good luck!