Sunday, 21 January 2018

Two Dimensional Array Of Characters


Two Dimensional Array Of Characters


Two Dimensional Array Of Characters
Our example program asks you to type your name.When you do so,it checks against a master
 list to see if you are worthy of entry to the palace.

Example: 

  #include "string.h"
  #define FOUND 1
  #define NOTFOUND 0
  main()
  {
   char masterlist[6][10]={"srujana",
                           "sneha",
                           "swathi",
                           "lavanya",
                           "ramya",
                           "kalyani"
                          };
   int i,flag,a;
   char yourname[10];
   printf("\n Enter your name:");
   scanf("%s",yourname);
   flag=NOTFOUND;
   for(i=0;i<=5;i++)
   {
     a=strcmp(&masterlist[i][0],yourname);
     if(a==0)
     {
      printf("welcome,u can enter the palace");
      flag=FOUND;
      break;
     }
   }
   if(flag==NOTFOUND)
   printf("sorry,u r a trespasser");
  }

OUTPUT:
Enter your name:keerthi
sorry,u r a trespasser

Enter your name:srujana
welcome,u can enter the palace.

Names can be supplied from keyboard as:
       for(i=0;i<=5;i++)
       scanf("%s",&masterlist[i][0]);
     while comapring the strings through strcmp() note that the addresses of strings are being passed to strcmp().
srujana\0  sneha\0  swathi\0 lavanya\0  ramya\0  kalyani\0
1001         1011       1021       1031        1041     1051
      Here 1001,1011,....are the base adresses of successive
names. For example, even though 10 bytes are reserved for storing the name "ramya", it occupies only 5 bytes. Thus 5 bytes go waste.

ARRAY OF POINTERS TO STRINGS :

 pointer variable always contains an address. Therefore,if we construct an array of pointers it would contain a number of addresses. Array of pointers can be stored as
            char *names[]={
                           "srujana",
                           "sneha",
                           "swathi",
                           "lavanya",
                           "ramya",
                           "kalyani"
                          };
    One reason to store strings in an array of pointers is to make more efficient use of available memory.

LIMITATIONS OF ARRAY OF POINTERS TO STRINGS:
    When  we are using a 2-D array of characters we are at liberty to either initialize the strings where we are declaring the array or receive the strings using scanf() function.

Example:        main()
{
char *names[6];
int i;
for(i=0;i<=5;i++)
        {
                  printf("\n enter name");
                  scanf("%s",names[i]);   /*doesnot work*/
                }
                }
     The program doesn't work because when we are declaring the  array it is containing garbage values. And it would be definitely wrong to send these garbage values to scanf() as
the addresses where it should keep the strings received from the keyboard.

0 comments:

Post a Comment