Reputation: 312
I have my struct like below , there can be n number of vendor
which can contain n number of test
struct.
I am trying to initialize this structure . This is a sample code I am trying , later I want to make it using macros and load the structure like X-macros.
I am also using flexible structure concept as I do not know how many test structs for a vendor are going to be. The data would be in a file , the struct needs to load all that is there. I have created a minimal sample code for SO. Below is my code.
#include <stdio.h>
typedef struct test{
int a;
int b;
int c;
}test;
typedef struct vendor{
int size;
test t[0];
}vendor;
vendor v[]={
{.size = 1, .t[] = {{1,2,3},}}
};
int main()
{
return 0;
}
I get this error -
a.c:16: error: expected expression before ‘]’ token
a.c:16: error: array index in initializer not of integer type
a.c:16: error: (near initialization for ‘v[0].t’)
a.c:16: error: extra brace group at end of initializer
a.c:16: error: (near initialization for ‘v[0]’)
a.c:16: error: extra brace group at end of initializer
a.c:16: error: (near initialization for ‘v[0]’)
a.c:16: warning: excess elements in struct initializer
a.c:16: warning: (near initialization for ‘v[0]’)
I have tried without flexible struct , no luck so far. any suggestions on how to init this struct ?
Upvotes: 1
Views: 2176
Reputation: 225817
The .t[]=
syntax in the initializer is invalid. When using a designated initializer, you only need to specify the name of the member:
.t={1, 2, 3}
However, this still won't work with a flexible array member.
The size of a struct with a flexible array member doesn't include space for the flexible array member, so you can't created a static or automatic instance of it. You need to allocate memory for the struct dynamically:
vendor *v;
void init()
{
v = malloc(sizeof(vendor) + 1 * sizeof(test));
v.size = 1;
v.t = (test){1, 2, 3};
}
int main()
{
init();
return 0;
}
Also, because of the variable size, a struct with a flexible array member cannon be a member of an array.
Upvotes: 3