C pointer application



We have used pointer in different ways. Tutorial will list out different pointer applications of c programming.

Pointer Applications in C Programming

Pointer is used for different purposes. Pointer is low level construct in programming which is used to perform high level task. Some of the pointer applications are listed below

A. Passing Parameter by Reference

First pointer application is to pass the variables to function using pass by reference scheme.

void interchange(int *num1,int *num2)
{
    int temp;
    temp  = *num1;
    *num1 = *num2;
    *num2 = *num1;
}

Pointer can be used to simulate passing parameter by reference. Pointer is used to pass parameter to function. In this scheme we are able to modify value at direct memory location.

Re-commanded Article : Ways of function calling

B. Accessing Array element

int main()
{
int a[5] = {1,2,3,4,5};
int *ptr;
ptr = a;

for(i=0;i<5;i++) {
 printf("%d",*(ptr+i));
}

return(0);
}

We can access array using pointer. We can store base address of array in pointer.

ptr = a;

Now we can access each and individual location using pointer.

for(i=0;i<5;i++) {
     printf("%d",*(ptr+i));
}

C. Dynamic Memory Allocation :

Another pointer application is to allocate memory dynamically.

We can use pointer to allocate memory dynamically. Malloc and calloc function is used to allocate memory dynamically.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str;

   str = (char *) malloc(15);
   strcpy(str, "mahesh");

   printf("String = %s,  Address = %u\n", str, str);
   free(str);
   
   return(0);
}

consider above example where we have used malloc() function to allocate memory dynamically.

D. Reducing size of parameter

struct student { 
   char name[10]; 
   int rollno; 
};

Suppose we want to pass the above structure to the function then we can pass structure to the function using pointer in order to save memory.

Suppose we pass actual structure then we need to allocate (10 + 4 = 14 Bytes(*)) of memory. If we pass pointer then we will require 4 bytes(*) of memory.

E. Some other pointer applications :

  1. Passing Strings to function
  2. Provides effective way of implementing the different data structures such as tree,graph,linked list

[Note :* Above example is written by considering the 64 bit compiler.)