Array of Strings in C

Array of pointers to string.First its important to recall what is string in C? In C string is an array of characters terminated by \0.string can be represented in two ways:
 char str[]="Hello";//str is string
 or
 char* str="Hello";//here str is pointer so it stores the base address of the string ie base addrees of the array of characters.

 So, Now its quite clear that array of pointer to string means array of base addresses of strings.

 char* stra[]={"Programmer","are","Great"};//stra is array of pointers.

 so stra[0] contains base address of "Programmers".
 so stra[1] contains base address of "are".
 so stra[2] contains base address of "Great".

full Example code:



#include<stdio.h>
int main()
{
    /*array of char* ie array of strings */
    char* arr[]={
                "Sony",
                "Mony",
                "Tony"
                };
    printf("\naddress of Sony is=arr[0]=%u",arr[0]);
    printf("\naddress of Mony is=arr[1]=%u",arr[1]);
    printf("\naddress of Tony is=arr[2]=%u\n",arr[2]);
 
    printf("\nvalue of arr[0]=%s",arr[0]);
    printf("\nvalue of arr[1]=%s",arr[1]);
    printf("\nvalue of arr[2]=%s\n",arr[2]);

return 0;
}
/*
address of Sony is=arr[0]=134514016
address of Mony is=arr[1]=134514021
address of Tony is=arr[2]=134514026

value of arr[0]=Sony
value of arr[1]=Mony
value of arr[2]=Tony
*/

No comments:

Post a Comment