零长数组

Arrays of Length Zero

这样说:

Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object

零长数组在GNU C中是允许的。结构体中最后一个元素,把他用作变长对象的头。Flexible array 即柔性数组。

但是在C++中,C++约定每个对象在内存中有唯一的地址,故零长数组在C++中其实长度是1

struct line {
       int length;
       char contents[0];
};
struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length);
thisline->length = this_length;

可能会有疑问这里为何不直接搞一个指针和len即可?

如果用指针的话,这里不能保证变长对象的地址和结构体连续。这里就是柔性数组的好处。

内存的连续:

  • 提升访问速度
  • 方便释放

转载于:https://www.cnblogs.com/stevinwang/articles/4087597.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值