I would like to define array size inside a structure by using a parameter of this structure. Does C permit to do something like this ?
struct queue {
int head;
int top;
int size;
struct action action[size];
};
I would like to define array size inside a structure by using a parameter of this structure. Does C permit to do something like this ?
struct queue {
int head;
int top;
int size;
struct action action[size];
};
No you can't. Since action
is not a dynamic variable, the compiler needs to know at compile time how much space it needs for action
. size
was not even initialized. Anyway, you could see this just by trying to compile.
The size
is not known at the time of defining the struct. Therefore it is impossible for the compiler to understand how large the result will be. Typically, you would first allocate memory for the struct, and have a struct action *action;
member. After initializing the struct, you use instance->action = calloc(instance->size, sizeof *instance->action)
to allocate memory for the array.