I’m working on an exercise in K&R (ex. 5–9) and I was trying to convert the original program’s 2D array of
static char daytab[2][13] = {
{0, 31, 28,
Just worked this problem in K&R myself, so maybe I can add to the really good answers already given. This is a good exercise in getting away from using 2-D arrays and towards using arrays of pointers. Note that at this point in the book we have not been introduced to malloc
. So, one approach would be to set up the month arrays beforehand, then an array of pointers to those arrays:
char y0[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char y1[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char *daytab[] = {y0, y1};
Recall that the name of an array is a pointer to the first element. Now you really have an array of pointers to two arrays of 13 int
s.