Pointers in C++
Pointers in C++ are special variables that store the address or memory location of another variable.
Syntax
datatype *variable_name;
int *x; // x can point to an address which holds int data
How to use Pointers?
To use pointers in C++, follow the steps below:
- Create a pointer variable.
- Assigning the address of another variable to a pointer using the unary operator (&).
- Accessing the value at the address using unary operator (*).
Example
#include <iostream>
using namespace std;
int main()
{
int var = 18;
int *ptr;
ptr = &var;
cout << "Initial value of var is: " << var << endl;
cout << "Initial value of *ptr is: " << *ptr << endl << endl;
// changing the value of var using ptr
*ptr = 47;
cout << "New value of *ptr is: " << *ptr << endl;
cout << "New value of var is: " << var << endl;
return 0;
}
Output
Initial value of var is: 18
Initial value of *ptr is: 18
New value of *ptr is: 47
New value of var is: 47
Initial value of *ptr is: 18
New value of *ptr is: 47
New value of var is: 47
Advantage of using Pointers in C++
- Pointers make us able to access any memory location in the computer's memory.
- Pointers improve speed performance.
- Pointers efficiently handle arrays and strings.
- Functions can return multiple values using Pointers.
- Pointers can reduce code and save memory.
Symbols used in pointer
Symbol | Name | Description |
---|---|---|
& (Ampersand) | Address operator | Used to determine the address of a variable. |
* (Asterisk) | Indirection operator | Used to access the value of an address. |