About Lesson
Let’s look at the following function, that demonstrates how pointer arrays are initialised:
/* Return the name of the month, given a number.
* Example: month_name(9) returns September.
*/
char *month_name(unsigned short n)
{
static char *months[] = {
"Invalid month",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
};
return n > 12 ? months[0] : months[n];
}
The initialiser 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 months[i]. As we haven’t specified the array size, the compiler counts the initialisers and uses that as the size.
Note that we need to declare months as static, since we are returning a pointer to the matching month name and the scope of automatic variables is the function boundary. So, if we return a pointer value to a string that is local, it would be invalid in the calling function.