Declaring zero size vector

后端 未结 4 931
萌比男神i
萌比男神i 2020-12-18 10:21

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

相关标签:
4条回答
  • 2020-12-18 10:35

    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\n", 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).

    0 讨论(0)
  • 2020-12-18 10:42

    Chris' answer is correct, but I'd probably allocate the object slightly 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' answer works since sizeof(char)==1, but for another type, you'd have to explicitly multiply by sizeof *bar.

    0 讨论(0)
  • 2020-12-18 10:49

    An array will also be accessed via pointers (indices are implicit pointers). So I suspect, if they tell you so, this will be interpreted like a pointer. As it’s a zero-length array it will probably point to the next value (I hope something follows in that struct?).

    This is suspection, not knowledge. :)

    It’s not how you would do anything though … If they want a pointer they should use a pointer. If they can’t tell you why it’s there it shouldn’t be.

    0 讨论(0)
  • 2020-12-18 10:52

    This should be a compiler-time error! Only dynamically allocated arrays can be allocated with 0 size.

    0 讨论(0)
提交回复
热议问题