too many initializers for 'int [0]' c++

60,609

Solution 1

In C++11, in-class member initializers are allowed, but basically act the same as initializing in a member initialization list. Therefore, the size of the array must be explicitly stated.

Stroustrup has a short explanation on his website here.

The error message means that you are providing too many items for an array of length 0, which is what int [] evaluates to in that context.

Solution 2

In the first example, something (actual memory allocation) is actually happening. The computer easily counts the number of items given to it and uses this as the capacity. In the second use, as part of a struct, the array is simply part of the template of a struct. In the second case, a size must explicitly be given and known at compile-time. There is no automatic counting here. It's in a similar vein to function declarations versus definitions as well as variable declarations (tells type but memory is untouched) and their invocation/use (where the program acts).

Solution 3

Probably cause in a struct the compiler needs you to specify the size explicitly.

C initialize array within structure (pun intended)

Solution 4

These are two completely different contexts:

The first is a variable declaration (with an initialiser clause).

The second is a type definition.

Share:
60,609
cppython
Author by

cppython

Updated on June 19, 2020

Comments

  • cppython
    cppython almost 4 years

    First:

    int k[] ={1,2,3,4,5};
    

    Second:

    struct slk
    {
        int k[] ={1,2,3,4,5};
    };
    

    for those two statements, why does the first one pass the compilation but the second one give me

    error:too many initializers for 'int [0]'. the compilation would passed if I set k[5];

    What does this error message means? Note: code tested on GNU GCC version 4.7.2

  • There is nothing we can do
    There is nothing we can do about 9 years
    I'm finding it silly. Identical construct and it compiler can deduce size in one case but not in the other. How inconsistent is that?