Array of pointers

0
26

We can have the array of pointers which is generally very useful in handling strings of varying length in a single array. Suppose we have to save 5 names in an array (Ram, Laxman, Sita, Dashavatar, Hanuman), then to save them we need a two-dimensional array of 5 rows and 10 columns at least because the 2-D array cannot be defined with different columns. Clearly, some columns are wasted for some names as they are not of that much size. Whereas with the help of array of pointers we can use as much memory needed as shown below: –

// Creating Five different Strings in memory.
  char str1[]= "Ram";
  char str2[]= "Sita";
  char str3[]= "Laxman";
  char str4[]= "Dashavatar";
  char str5[]= "Hanuman";
  char *pointer_name[5];    // An array of pointers to hold char addresses
  // Assigning the addresses of strings to five pointers
  pointer_name[0] = str1;    
  pointer_name[1] = str2;
  pointer_name[2] = str3;
  pointer_name[3] = str4;
  pointer_name[4] = str5;

Now see same array without using pointer

char array_name[5][15] = {"Ram", "Sita", "Laxman", "Dashavatar", "Hanuman"};

Now in memory they will be represented as below: –

In the first case, five names will be stored at five locations occupying (3+4+6+10+7 = 30) bytes for strings and 5 bytes for storing 5 pointers. In the second case, a consecutive space of (5×15= 75) bytes is required in memory. As the names increase, this gap will increase resulting in memory wastage in the second case. Following program will use them: –

#include<stdio.h>
int main() 
{
  int i=0,j=0;
  // Creating Five different Strings in memory.
  char str1[]= "Ram";
  char str2[]= "Sita";
  char str3[]= "Laxman";
  char str4[]= "Dashavatar";
  char str5[]= "Hanuman";
  // An array of pointers to hold char addresses
  char *pointer_name[5];	
  // Assigning the addresses of strings to five pointers
  pointer_name[0] = str1;	
  pointer_name[1] = str2;
  pointer_name[2] = str3;
  pointer_name[3] = str4;
  pointer_name[4] = str5;
  for(i=0; i<5; i++) 
  printf("%s\n",pointer_name[i]);
  char array_name[5][15] = {"Ram", "Sita", "Laxman", "Dashavatar", "Hanuman"};
  for(i=0; i<5; i++)
  {
    for(j=0; j<15; j++)
    {
      printf("%c",array_name[i][j]);
    }
    printf("\n");
  }
  return 0;
}
Ram
Sita
Laxman
Dashavatar
Hanuman
Ram
Sita
Laxman
Dashavatar
Hanuman

LEAVE A REPLY

Please enter your comment!
Please enter your name here