C pointer application

Application of Pointer in C Programming

Pointer is used for different purposes. Pointer is low level construct in programming which is used to perform high level task.

A. Passing Parameter by Reference

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.

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 :

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

D. Passing Parameter to the function :

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 of the 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.)