gpt4 book ai didi

c - 声明零大小 vector

转载 作者:太空狗 更新时间:2023-10-29 15:22:51 25 4
gpt4 key购买 nike

下面是什么意思?

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

我问过我的同事,他们告诉我这和写 void* bar 是一样的。

据我所知,C 指针只是一个 4 字节变量(至少在 32 位机器上是这样)。编译器如何知道 bar[0] 是一个指针(因此有 4 个字节长)?那只是语法糖吗?

最佳答案

你的同事撒谎了。 (虽然可能不是故意的,所以不要对他们或任何事情生气。)

这叫做灵活数组成员,在C99中写成char bar[];,在C89中写成char bar[1];,有些编译器会让你写成 char bar[0];。基本上,您只使用指向结构的指针,并在末尾为它们分配一定量的额外空间:

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);

那样,p->bar 存储一个字符串,其大小不受数组声明的限制,但仍然与 结构的其余部分在相同的分配中完成 (而不是需要成员是 char * 并且需要两个 malloc 和两个 free 来设置它) .

关于c - 声明零大小 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4255193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com