Excess elements of scalar initializer for pointer to array of ints

前端 未结 3 838
情书的邮戳
情书的邮戳 2020-12-13 00:16

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,          


        
3条回答
  •  一生所求
    2020-12-13 01:17

    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 ints.

提交回复
热议问题