Arrays of String Pointers
Completed
Store the month names in char *months[12]. Read month numbers and print each name, or invalid.
Input
n, then n integers.
Output
n lines.
Example
Input
3 1 10 13
Output
January October invalid
Editor
C
Hints
Each element is a pointer to a string literal.
Solution explanation
An array of char * uses less memory than a 2D char array when strings vary in length.
Show solution
#include <stdio.h>
int main() {
char *months[12];
months[0] = "January"; months[1] = "February"; months[2] = "March";
months[3] = "April"; months[4] = "May"; months[5] = "June";
months[6] = "July"; months[7] = "August"; months[8] = "September";
months[9] = "October"; months[10] = "November"; months[11] = "December";
int n, m;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &m);
if (m >= 1 && m <= 12) printf("%s\n", months[m - 1]);
else printf("invalid\n");
}
return 0;
}