Pointers and References in C++
Pointers and references are two of the most powerful features of C++. A pointer is a variable that holds the address of another variable, while a reference is an alias for another variable.
Let’s look at an example of declaring and using a pointer:
#include <iostream>
int main()
{
int x = 10;
int *ptr = &x;
std::cout << "x = " << x << std::endl;
std::cout << "ptr = " << ptr << std::endl;
*ptr = 20;
std::cout << "x = " << x << std::endl;
return 0;
}
Output
x = 10
ptr = 0x7ffee5e90d4c
x = 20
In this example, we have declared a pointer called ptr and initialized it with the address of the variable x. We have then used the cout stream to print out the value of x and the address of ptr. Finally, we have used the dereference operator (*) to change the value of x.