Structures initializer

1) In short this would work:
struct s_months {
char const *name_;
// char const name_[];
int days_;
};

s_months const smonths[2] = { {"January", 31}, {"February", 28} };

No surprises since string literal defined as array of constant characters or pointer to constant character in C++

2) char const name[] = "January"; No problem too.

3) Why would this not work?

struct s_months {
// char const *name_;
char const name[];
int days_;
};

s_months const smonths[n_months] = { {"January", 31}, {"February", 28} };

Compilation error:
error: initializer-string for array of chars is too long

I find this error weird. Am i missing something here?
Please advice.
Thanks.
You can't declare an array as
T array[];
The size has to be known at compile-time, otherwise sizes can't be calculated, so there are only two valid array declarations:
1
2
T array[k];
T array[]={...};
The second form can't be used for members except in this case:
1
2
3
4
struct A{
    static const T array[];
};
const T A::array[]="...";
Last edited on
Thanks ..
I understand now about why that format couldn't be as a member since that would make that structure of variable size ..
I don't understand the second form you mention. I am new to C++. Is that second form you mention is a further topic in C++ (template??) .. If so for now i will ignore that (havent reach reading that topic yet). :OP Please advice. Thanks
Topic archived. No new replies allowed.