0

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];
};
zhifir
  • 17
  • 6
  • 1
    @PhilippClaßen it was closed because the duplicate answer tells exactly about flexible array members. – bereal May 17 '20 at 16:11

2 Answers2

-1

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.

Francesco
  • 897
  • 8
  • 22
  • 1
    You seem to have missed the "something like this" part, and something like this is certainly possible with flexible array members, see the referred question. – bereal May 17 '20 at 16:04
  • In the referred question, in the answers the code contains pointers. Here there are no pointers. But if you think you can do this, why don't you try to compile it? If I try to compile the code I get this `main.c:5:26: error: ‘size’ undeclared here (not in a function) struct action action[size];`, like I was expecting in the answer – Francesco May 17 '20 at 16:09
  • Kindly explain your understanding of "something like this" clause. – bereal May 17 '20 at 16:10
  • I think "something like this" means "if you try this code or something near this code". I wouldn't consider using pointers and malloc something like the code inserted. – Francesco May 17 '20 at 16:12
  • 1
    Something like this is, to quote, "_define array size inside a structure by using a parameter of this structure_", and that's _exactly_ what FLAs are for. – bereal May 17 '20 at 16:16
  • 1
    Bereal is right, that was my question. Sorry if it's unclear. And I got the answer, thank you all. – zhifir May 17 '20 at 16:25
-2

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.

Cheatah
  • 1,825
  • 2
  • 13
  • 21