The C standard states (emphasize mine):
21 EXAMPLE 2 After the declaration:
struct s { int n; double d[]; };
the structure struct
s
has a flexible array memberd
. [...]
22 Following the above declaration:
struct s t1 = { 0 }; // valid struct s t2 = { 1, { 4.2 }}; // invalid t1.n = 4; // valid t1.d[0] = 4.2; // might be undefined behavior
The initialization of
t2
is invalid (and violates a constraint) becausestruct s
is treated as if it did not contain memberd
.Source: C18, §6.7.2.1/20 + /21
I do not understand the explanation of "because struct s
is treated as if it did not contain member d
"
If I use the initializer of { 1, { 4.2 }};
, the { 4.2 }
part is to initialize the flexible array member;
To be precise to initialize the flexible array member to be consisted of one element and initialize this element to the value 4.2
and thus stuct s
is treated as it has member d
or not?
This sentence makes no sense in my eyes.
- Why does the standard say, that
{ 4.2 }
wouldn't initialize/denote the flexible array member and thus the structure would be treated as if it has no memberd
?
If I use a fixed size array, this notation works and initializes the member with no complain:
struct foo {
int x;
double y[1];
};
int main (void)
{
struct foo a = { 1, { 2.3 } };
}
- Why is this initialization invalid when the structure has an flexible array member but valid when the structure has an fixed size array member?
Could you elaborate that?
I've read:
Why does static initialization of flexible array member work?
and
How to initialize a structure with flexible array member
and
Flexible array members can lead to undefined behavior?
and others but none of them answers me what this sentence wants to explain and why exactly this this is invalid.
Related: