I was reading about zero-length arrays, where and how it is used and all. And I understood that they are used when one want a dynamically sized member in one's structure. It is different from using a pointer because
- It lets you allocate the memory for the struct and for variable-length the array at the end of the struct as one continuous memory block.
- If you used a pointer, you'd either have to allocate memory separately (two malloc calls, likely non-continuous) or use some other tricks (to achieve proper alignment etc.).
as taken from this answer.
Now, all this is good and ok. Until I read some more older facts about this issue.
Fact 1
- In ISO C90, you would have to give contents a length of 1, which means either you waste space or complicate the argument to
malloc
.
Fact 2
- GCC allows this feature as an extension.
Now I really don't know what an extension means here. But what I am thinking about is about Fact 1. More explanation ahead.
Lets look at some code.
#include<stdio.h>
#include<stdlib.h>
struct line
{
int len;
char* content;
};
int main()
{
int i;
struct line* p = malloc(sizeof(struct line) + 10);
p->len = 10;
p->content = (char*)(&(p->len) + 1);
printf("%p\n", &(p->len));
for(i = 0; i < 10; i++)
{
printf("%p\n", &(p->content[i]));
}
}
This piece of code that I came up with effectively implements all the features of the zero-length array. May be there is a line of code extra, but it is definitely better then the bad effects Fact 1 has.
So, my question is, was there any particular reason why the above way (demonstrated in the code above) was not used and they had to add an extension to GCC, or use an array of size 1
.