Introduction
C++ reference and pointer appear to be similar. However, there are a few variations that exist among them. A reference is a variable, and we can call it another name of that existing variable, even as the pointer is a variable that stores the memory address of that existing variable.
Also see, Literals in C, Fibonacci Series in C++
Pointers
- A pointer is a variable that consists of the address of another variable.
- It may be dereferenced with the assistance of the (*) operator.
- By using the *operator, we can access that memory location where the pointer points.
C++ code for pointers
// C++ program to demonstrate use of * for pointers in C++
#include <iostream>
using namespace std;
int main()
{
// variable declared and value assigned
int v = 10;
// A pointer variable p that holds the address of v.
int *p = &v;
// This line prints value at address stored in p.
// Value stored is value of variable "v"
cout << "Value of v = "<< *p << endl;
//Address may be different for different machines
cout << "Address of v = " << p << endl;
// Value at address is now 20
*p = 20;
// This prints 20
cout << "After doing *p = 20, *p is "<< *p << endl;
return 0;
}
Output:
Value of v = 10
Address of v = 0x7ffe6ea2b294
After doing *p = 20, *p is 20