Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

c - Declaring zero size vector

What does the following mean?

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

I asked my colleagues and they told me it's the same as writing void* bar.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your colleagues lied. (Probably not intentionally though so don't get mad at them or anything.)

This is called a flexible array member, and in C99 is written as char bar[];, and in C89 was written as char bar[1];, and which some compilers would let you write as char bar[0];. Basically, you only use pointers to the structure, and allocate them all with an amount of 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
", p->bar);

That way, p->bar stores a string whose size isn't limited by an array declaration, but which is still all done in the same allocation as the rest of the struct (rather than needing the member to be a char * and need two mallocs and two frees to set it up).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...