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.