0
  struct site
  {
    char name[];
    int no_of_pages;
  };

Is this declaration valid in C (for the a=character array name). I am getting an error that the array needs a size!

The error I got: flexible array member 'name' with type 'char []' is not at the end of struct char name[];

coder746
  • 13
  • 1

1 Answers1

0

These need to be at the end of the structure so that the structure's memory can be extended to include them. There's no way to "accordion" out from the middle.

The way you add to this is to "over-allocate" for that structure, like sizeof(struct site) + sizeof(char) * N. The additional memory you allocate becomes available for use as part of that name property.

In general this is a bad plan for simple things like this where what you really need is char* and to copy any string buffer allocations in there either with malloc() and strcpy() or strdup() if you have access to POSIX functions.

So you have two options:

struct site
{
  int no_of_pages;
  char name[];
};

Where this necessarily means you cannot have any other "extensible" properties, or this:

struct site
{
  char* name;
  int no_of_pages;
};

Where you can have as many as you want.

A better example for where this technique is useful is if you have a variable length array with metadata, like this:

struct page {
  char *name;
  int links_count;
  struct link links[];
}

Where now you can over-allocate and make use of this links array at the end easily. This could be converted to struct link links* and allocated independently, but that involves two allocations instead of one, so it might have drawbacks. You need to consider use of this technique very carefully.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • BTW, can it be considered a Struct Hack? – Arkadiusz Drabczyk Mar 21 '21 at 18:16
  • 1
    @ArkadiuszDrabczyk It's somewhat hacky, but sometimes it's an elegant solution to a difficult problem. It depends entirely on context. I'd recommend avoiding it, like I have here with `char*` as a substitute. – tadman Mar 21 '21 at 18:17
  • I was referring to the C idiom https://www.google.com/search?q=Struct+Hack. – Arkadiusz Drabczyk Mar 21 '21 at 18:18
  • @ArkadiuszDrabczyk Ah, then yes. – tadman Mar 21 '21 at 18:20
  • Thank you @tadman! – coder746 Mar 21 '21 at 18:20
  • @ArkadiuszDrabczyk: No, it is not the “Struct Hack.” GCC, and possibly other compilers, allowed a zero-length array (declared with `[0]`) in a structure as a method of implementing structures with array sizes determined during program execution. The C standard changed to support this using an array declared with `[]` at the end of the structure. When you use the latter, it is behavior defined by the C standard, not a hack. – Eric Postpischil Mar 21 '21 at 19:06