How to create a pointer for strings using C language?

CServer Side ProgrammingProgramming

Arrays of pointers (to strings)

Array of pointers is an array whose elements are pointers to the base address of the string.

It is declared and initialized as follows −

char *a[3 ] = {"one", "two", "three"};
//Here, a[0] is a ptr to the base add of the string "one"
//a[1] is a ptr to the base add of the string "two"
//a[2] is a ptr to the base add of the string "three"

Advantages

  • Unlink the two-dimensional array of characters. In (array of strings), in array of pointers to strings there is no fixed memory size for storage.

  • The strings occupy as many bytes as required hence, there is no wastage of space.

Example 1

#include<stdio.h>
main (){
   char *a[5] = {“one”, “two”, “three”, “four”, “five”};//declaring array of pointers to
   string at compile time
   int i;
   printf ( “The strings are:”)
   for (i=0; i<5; i++)
      printf (“%s”, a[i]); //printing array of strings
   getch ();
}

Output

The strings are: one two three four five

Example 2

Consider another example on array of pointers for strings −

#include <stdio.h>
#include <String.h>
int main(){
   //initializing the pointer string array
   char *students[]={"bhanu","ramu","hari","pinky",};
   int i,j,a;
   printf("The names of students are:\n");
   for(i=0 ;i<4 ;i++ )
      printf("%s\n",students[i]);
   return 0;
}

Output

The names of students are:
bhanu
ramu
hari
pinky
raja
Published on 08-Mar-2021 14:13:37
Advertisements