灵活的阵列成员(零长度阵列) [英] Flexible Array Member (Zero Length Array)

查看:132
本文介绍了灵活的阵列成员(零长度阵列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在参考 GCC的零长度阵列解释:

这是的情况下是特别有用的,当一个结构为可变长度对象的标题。这也正是我的情况。此外,我关心我的结构在堆中的对齐方式。

This is particularly useful in the case when a struct is a header for a variable-length object. This is exactly my case. Furthermore, I am concerned with the alignment of my structs in the heap.

在这种情况下,我还真不明白什么是关于零长度数组是有用的。他们如何与这个特殊的情况?

In this case, I still really do not understand what's useful about zero length arrays. How are they related to this particular situation?

编辑:

难道我可以把尽可能多的数据,因为我想在那里?

Is it that I can put as much "data" as I want in there?

推荐答案

基本上,它可以让你有一个结构,在结束变长数组:

Basically it allows you to have a structure with a variable length array at the end:

struct X {
  int first;
  int rest[0];
};

由于C不真正关心您正在访问的元素超出了数组的末尾,你只是大小为0的数组开始,然后分配足够的内存来处理你真正想要然而,许多元素:

Since C doesn't really care that you are accessing elements beyond the end of the array, you just start with an array of size zero, and then allocate enough memory to handle however many elements you actually want:

struct X *xp = (struct X *)malloc(sizeof(struct X)+10*sizeof(int));
xp->rest[9] = 0;

这篇关于灵活的阵列成员(零长度阵列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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