Declaring zero size vector

后端 未结 4 930
萌比男神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: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.

提交回复
热议问题