Programming

What is Pointer in C and C++

As the name suggest, a pointer is used to point a particular object. In programming world, the concept is same, here pointer is used to store address or memory location of variable .

Example:   int a = 5;

Loading...

           int *ptr = a;

pointer in C++

But Why Use Pointer ?

Well it can understand through a real life example. Consider a courier is to be delivered to a place, then address is the best and fastest method to deliver. Similarily, there is large number of memory locations and to access any part of it, you need to have a address for that location.

A pointer is represented by (*) and an address is represented by &. To access the value stored in the address we use the unary operator (*) that returns the value of the variable located at the address specified by its operand. This is also called Dereferencing. Pointers can be used with 1D arrays and 2D arrays. A pointer can point to another pointer also.

#include<iostream>
using namespace std;

int main()
{
    int a = 5;
    cout<< "Variable a has value" << a << endl;
    int *ptr = &a;
    int **p = &ptr;   // pointer of a pointer 
    cout<<"Address of that location is" << &a << endl;
    cout<<"Value of the pointer ptr is " << ptr << endl;
    cout<<"Value of the pointer p is " << p << endl;
    return 0;
}

Output :

Variable a has value 5
Address of that location is 0x6ffe34
Value of the pointer ptr is 0x6ffe34

Expressions and Arithmetic operations on pointer

You can perform following operations on pointer:

Loading...
  • Increment (++)
  • Decrement (–)
  • Subtraction (-=)
  • Addition (+=)
#include <bits/stdc++.h> 
using namespace std;

int main() 
{ 
    // Declare an array 
    int v[5] = {10, 100, 200, 300, 400}; 
  
    // Declare pointer variable 
    int *ptr; 
  
    // Assign the address of v[0] to ptr 
    ptr = v; 
  
    for (int i = 0; i < 5; i++) 
    { 
        printf("Value of *ptr = %d\n", *ptr); 
        printf("Value of ptr = %p\n\n", ptr); 
  
        // Increment pointer ptr by 1 
        ptr++; 
    } 
} 

Show More
Back to top button