Arrays of Strings in c
Besides data base applications, another common application of two dimensional arrays is to store an array of strings. In this section we see how an array of strings can be declared and operations such as reading, printing and sorting can be performed on them.
A string is an array of characters; so, an array of strings is an array of arrays of characters. Of course, the maximum size is the same for all the strings stored in a two dimensional array. We can declare a two dimensional character array of MAX strings of size SIZE as follows:
char names[MAX][SIZE];
Since names is an array of character arrays, names[i] is the character array, i.e. it points to the character array or string, and may be used as a string of maximum size SIZE - 1. As usual with strings, aNULL character must terminate each character string in the array. We can think of an array of strings as a table of strings, where each row of the table is a string as seen in Figure
We will need an array of strings in our next task to read strings, store them in an array, and print them.
NAMES: Read and store a set of strings. Print the strings.
We can store a string into names[i] by reading a string using or by copying one into it using strcpy(). Since our task is to read strings, we will use gets(). The algorithm is simple:
while array not exhausted and not end of file, read a string into an array element print out the strings in the array of strings
We will organize the program in several source files since we will be using some of the functions in several example programs. The program driver and the header file are shown
The program reads character strings into an array, in this case, names. The program can, of course, serve to read in any strings. The for loop in main() reads strings into an array using gets() to read a string into names[n], the row of the array. That is, the string is stored where names[n] points to. The variable n keeps track of the number of names read. The loop is terminated either if the number of names equals MAX, or when gets() returns NULL indicating end of file has been reached. Next, the program calls on printstrtab() to print the names stored in the two dimensional array, names. The arguments passed are the array of strings and the number of strings, n.