Excess elements of scalar initializer for pointer to array of ints

前端 未结 3 846
情书的邮戳
情书的邮戳 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:20

    @Dmitri explained it well, but I wanted to add that

    static char (*daytab)[13] = { ... };
    

    is one pointer to an array of 13 char elements. The compiler gives you the warning because you've passed in two arrays. It's like trying to assign two addresses to one pointer char *p = {a, b}. There are more elements than necessary per your declaration. See Geekforgeek's explanation on what an array pointer really means.

    As for answering the K&R exercise, consider

    Option 1:

    static char *daytab[2] = { 
        (char []) {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
        (char []) {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
        };} 
    

    or Option 2:

    static char (*daytab)[13] = (char [][13]) { 
        {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
        {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
        };} 
    

    Option 1 is an array of two char pointers.

    Option 2 is one array pointer. It points to an array of 13 char elements. Just as you could increment a char pointer to get the next letter in a string, you can increment this array pointer to grab the next array of 13 chars.

提交回复
热议问题