Zero-size vector declaration

What does the following mean?

struct foo { ... char bar[0]; // Zero size??? }; 

I asked my colleagues and they told me this the same way as writing void* bar .

As far as I know, a C-pointer is just a 4-byte variable (at least on a 32-bit machine). How does the compiler know that bar [0] is a pointer (and therefore 4 bytes)? Is it just syntactic sugar?

+4
c
source share
4 answers

Your colleagues lied. (Probably not intentionally, although do not be angry with them or anything else.)

This is called the flexible element of the array, and is written as char bar[]; in C99 char bar[]; , and in C89 - as a char bar[1]; , and some compilers allow you to write as char bar[0]; . Basically, you only use structure pointers and allocate them all with extra space at the end:

 const size_t i = sizeof("Hello, world!"); struct foo *p = malloc(offsetof(struct foo, bar) + i); memcpy(p->bar, "Hello, world!", i); // initialize other members of p printf("%s\n", p->bar); 

Thus, p->bar stores a string whose size is not limited by the declaration of the array, but is still executed in the same distribution as the rest of the struct (instead of the member being char * and installing it requires two malloc and two free )

+5
source share

Chris's answer is correct, but I would probably select the object a little differently.

 int n = ...; // number of elements you want struct foo *p = malloc(offsetof(struct foo, bar[n])); 

then iterate over it with

 for (int i = 0; i < n; ++i) { p->bar[i] = ...; } 

The key point is that Chris's answer works with sizeof(char)==1 , but for another type you have to explicitly multiply by sizeof *bar .

+3
source share

It must be a compiler time error! Only dynamically allocated arrays can be allocated with size 0.

0
source share

The array will also be accessible via pointers (indexes are implicit pointers). Therefore, I suspect that if they tell you this, it will be interpreted as a pointer. Like its zero-length array, it will probably point to the following value (hope something follows in this structure?).

This is suspicion, not knowledge. :)

Not like you would do everything, though ... If they want a pointer, they should use a pointer. If they cannot tell you why it should not be there.

0
source share

All Articles