5.8 Initialization of Pointer Arrays
Consider the problem of writing a function month_name(n), which returns a pointer to a character string containing the name of the n-th month. This is an ideal application for an internal static array. month_name contains a private array of character strings, and returns a pointer to the proper one when called. This section shows how that array of names is initialized.
The syntax is similar to previous initializations:
1 /* month_name: return name of n-th month */
2 char *month_name(int n)
3 {
4 static char *name[] = {
5 "Illegal month",
6 "January", "February", "March",
7 "April", "May", "June",
8 "July", "August", "September",
9 "October", "November", "December"
10 };
11
12 return (n < 1 || n > 12) ? name[0] : name[n];
13 }
The declaration of name, which is an array of character pointers, is the same as lineptr in the sorting example. The initializer is a list of character strings; each is assigned to the corresponding position in the array. The characters of the i-th string are placed somewhere, and a pointer to them is stored in name[i]. Since the size of the array name is not specified, the compiler counts the initializers and fills in the correct number.