声明零大小的矢量 [英] Declaring zero size vector

查看:129
本文介绍了声明零大小的矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是下面的意思吗?

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

我问我的同事,他们告诉我,这是一样的书写无效*栏

据我了解C指针仅仅是一个4字节变量(至少在32位机器上)。编译器怎么知道吧[0]是指针(因此4个字节长)?那是只是语法糖吗?

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?

推荐答案

您的同事撒谎。 (可能不是故意,虽然所以不要针对他们或任何东西疯了。)

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

这就是所谓的柔性阵列成员,并在C99写成字符酒吧[]; ,并在C89被写成炭棒[1]; ,和一些编译器将让你写的字符酒吧[0]; 。基本上,仅使用指针的结构中,并用额外的空间的量在端分配他们所有

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

这样, P-GT&;酒吧存储一个字符串,它的大小不是由一个数组声明的限制,但在相同配置的它仍然是全部完成其余的结构(而不是需要的构件是的char * ,需要两个的malloc 和两个免费 s到设置它)。

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

这篇关于声明零大小的矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆