Pointers in C++

Pointers in C++ can be defined as a variable whose value points to the address of another variable. Pointers can dynamically allocate the memory. While the pointer variable holds the address of the variable. And the pointers in C++ variable can also be known as locator (or) indicator.

pointers in C++

Pointers in C++

The address of the memory is a numeric value. And it can be accessed by using variables identifier. If needed You can see this address by using the address-of operator (&) in front of the variable. While a declaration of the pointer is the same as the declaration of a simple variable except for use of * in the declaration.

Advantages of Pointers in C++

There are different types of pointers in C++. They are as follows:

  • Saves the memory.
  • Reduce the length and complexity of the program.
  • It increases the processing speed.
  • Allows passing of arrays and strings to functions more efficiently.
  • It helps us to return more than one value from the functions.
  • It makes you able to access any memory location in the computer’s memory.

Symbols Used in Pointers

Symbol Name Description
& (ampersand sign) Address operator Determine the address of a variable
* (asterisk sign) Indirection operator Access the value of an address

Using Pointers

  • Define a pointer variable
  • Assigning the address of a variable to a pointer using unary operator (&) which returns the address of that variable.
  • Accessing the value stored in the address using unary operator (*) which returns the value of the variable located at the address specified by its operand.

Syntax: type *variable_name;

Declaring a Pointer in C++

int ∗a; //pointer to int    
char ∗c; //pointer to char

If you want to allocate memory for an array, you will have to useas follows:

Syntax: new data_type[size_of_array];

Example:

#include<bits/stdc++.h> 
using namespace std; 
void geeks() 
{ 
  int var=20;  
//declare pointer variable     
    int *ptr;  
//note that data type of ptr and var must be same 
   ptr = &var;     
//assign the address of a variable to a pointer 
   cout<<"Value at ptr = " << ptr << "\n"; 
   cout<<"Value at var = " << var << "\n"; 
   cout<<"Value at *ptr = " << *ptr << "\n";      
}

Output:

Value at ptr = 0x7fff480bf3fc
Value at var = 20
Value at *ptr = 20

Example 2: 

#include <iostream>
using namespace std;
int main ()
{
   int  n = 20, *ptr;  /* actual and pointer variable declaration */
   ptr = &n;  /* store address of n in pointer variable*/ 
   cout << "Address of n variable: " << &n << endl;
   cout << "Address stored in pntr variable:"<<ptr<<endl; /* print address stored in pointer variable */
   cout << "Value of *pntr variable: " << *ptr << endl; /*print access the value using the pointer*/   
   system("pause");
   return 0;
}

Output:

Address of n variable: 0x7ffd8764cd64
Address stored in pntr variable:0x7ffd8764cd64
Value of *pntr variable: 20