Applications of Pointers in C/C++


To access array elements

We can access array elements by using pointers.

In C

Example

 Live Demo

#include <stdio.h>
int main() {
   int a[] = { 60, 70, 20, 40 };
   printf("%d\n", *(a + 1));
   return 0;
}

Output

70

In C++

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a[] = { 60, 70, 20, 40 };
   cout<<*(a + 1);
   return 0;
}

Output

70

Dynamic Memory Allocation

To dynamically allocate memory we use pointers.

In C

Example

 Live Demo

#include <stdio.h>
#include <stdlib.h>
int main() {
   int i, *ptr;
   ptr = (int*) malloc(3 * sizeof(int));
   if(ptr == NULL) {
      printf("Error! memory not allocated.");
      exit(0);
   }
   *(ptr+0)=1;
   *(ptr+1)=2;
   *(ptr+2)=3;
   printf("Elements are:");
   for(i = 0; i < 3; i++) {
      printf("%d ", *(ptr + i));
   }
   free(ptr);
   return 0;
}

Output

Elements are:1 2 3

In C++

Example

 Live Demo

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
   int i, *ptr;
   ptr = (int*) malloc(3 * sizeof(int));
   if(ptr == NULL) {
      cout<<"Error! memory not allocated.";
      exit(0);
   }
   *(ptr+0)=1;
   *(ptr+1)=2;
   *(ptr+2)=3;
   cout<<"Elements are:";
   for(i = 0; i < 3; i++) {
      cout<< *(ptr + i);
   }
   free(ptr);
   return 0;
}

Output

Elements are:1 2 3

Passing arguments to a function as a reference

We can use pointers to pass arguments by reference in functions to increase efficiency.

In C

Example

 Live Demo

#include <stdio.h>
void swap(int* a, int* b) {
   int t= *a;
   *a= *b;
   *b = t;
}
int main() {
   int m = 7, n= 6;
   swap(&m, &n);
   printf("%d %d\n", m, n);
   return 0;
}

Output

6 7

In C++

Example

 Live Demo

#include <iostream>
using namespace std;
void swap(int* a, int* b) {
   int t= *a;
   *a= *b;
   *b = t;
}
int main() {
   int m = 7, n= 6;
   swap(&m, &n);
   cout<< m<<n;
   return 0;
}

Output

67

To implement data structures like linked list, tree we can use pointers also.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements