Write a program to understand the concept of pointers in C language?

CServer Side ProgrammingProgramming

Pointer is a variable which stores the address of other variable.

Features of Pointers

Following are the features of pointers −

  • Saves the memory space

  • Execution time is faster because of direct access to memory location.

  • The memory is accessed efficiently with the pointer i.e. dynamically memory is allocated and deallocated.

  • Pointers are used with data structures.

Here is an example for search demonstration −

We can access and print a particular character in a string by using pointers.

Following example shows how to access the elements using pointer −

Example

 Live Demo

#include<stdio.h>
int main(){
   char array[5] = "Tutorial", *ptr, i, *ptr1;
   ptr = &array[1];
   ptr1 = ptr + 3;
   *ptr1 = 101;
   for(i = 0; i < 4;i++)
      printf("%c", *ptr++);
   return 0;
}

Output

In the above program, we assigned the starting value of pointer variable is with the address of second element in an array i.e) Tutorial. Then we add the value 101 i.e)'e' to the ptr variable. Thus it prints utoe.

utoe

Let us consider another example as follows −

Example

 Live Demo

#include<stdio.h>
int main(){
   char string[10] = "CprogRamming", *p, i, *p1;
   p = &string[5];
   p1 = p + 3;
   *p1 = 101;
   for(i = 0; i < 4;i++)
      printf("%c", *p++);
   return 0;
}

Output

Rame
raja
Published on 08-Mar-2021 14:12:20
Advertisements