Preview
Array of strings in c language with examples | String array in C Language
It is actually a two dimensional array of char type.
Example: char names[6][30];
In above example, names is an array of strings which can contain 6 string values. Each of the string value can contain maximum 30 characters.
1. Initialization of array of strings
We can initialize an array of strings just as we initialize a normal array The way to initialize an array of strings is
char var_name[R][C]={List of String values};
char specifies that we are declaring an array of strings.
Var_name refers to the array of strings defined by the programmer. The string array name should follow all the rules of a valid identifier of C Language.
[ ] [ ] Pair of square brackets specifies that it is an array of strings.
R specifies the maximum number of string values which can be stored in string array.
C specifies the maximum number of characters which can be stored in each string value stored in string array.
List of String values specifies various string values which are to be stored into string array. The list of string values must be enclosed between braces.
Example
char names[3][20]={“Lovejot”,”Ajay”,”Amit”};
In the above example, string array names has been initialized with three values “Lovejot”, “Ajay” and “Amit”.
Program to initialize an array of strings |
#include<stdio.h> int main() { char names[3][20]={“Lovejot”,”Ajay”,”Amit”}; int i; printf(”\nElements of string array are”); for(i=0;i<3;i++) printf(“\n%s”,names[i]); return(0); } |
Output |
Elements of string array are
Lovejot
Ajay
Amit
|
2. Reading and displaying array of strings
We can read and display an array of strings just as we read and display an array of other data types.
Program to read an array of strings. |
#include<stdio.h> int main() { char names[3][20]; int i; printf(”\nEnter three string values\n”); for(i=0;i<3;i++) gets(names[i]); printf(”\nElements of string array are”); for(i=0;i<3;i++) printf(“\n%s”,names[i]); return (0); } |
Output |
Enter three string values Lovejot Ajay Amit Elements of string array are Lovejot Ajay Amit |