What is Pointer in C and C++ | Quick Example

Pointer in C and C++

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

Example:   int a = 5;

           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 the address is the best and fastest method to deliver. Similarly, there is a large number of memory locations and to access any part of it, you need to have an address for that location.

what is pointer in c and c++ | quick example

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.

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 a value 5
The address of that location is 0x6ffe34
The value of the pointer ptr is 0x6ffe34

Expressions and Arithmetic operations on pointer

You can perform the following operations on the pointer:

  • 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 = %dn", *ptr); 
        printf("Value of ptr = %pnn", ptr); 
        // Increment pointer ptr by 1 

Show More

Related Articles

Leave a Reply

Back to top button