gpt4 book ai didi

c - C90 中的可变长度结构

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

GNU C 中允许使用零长度数组。并且可以这样初始化

struct line {
int length;
char contents[0];
};

struct line *thisline = (struct line *)
malloc (sizeof (struct line) + this_length);
thisline->length = this_length;

注意:我在这里指的是这个页面:http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html(提供 C 中可变长度结构的基本介绍)

它接着说:“在 ISO C90 中,您必须将内容的长度设置为 1,这意味着您要么浪费空间,要么使 malloc 的参数复杂化。”

这是什么意思?有人可以提供一个示例,说明如何在 C90 中初始化可变长度结构以帮助理解吗?

最佳答案

如果您真的必须使用 c90,那么 C FAQQuestion 2.6 中对此进行了介绍:

struct name {
int namelen;
char namestr[1];
};

struct name *ret =
malloc(sizeof(struct name)-1 + strlen(newname)+1);
/* -1 for initial [1]; +1 for \0 */

虽然 FAQ 确实说:

It's not clear if it's legal or portable, but it is rather popular. An implementation of the technique might look something like this.

虽然 gcc 文档基本上说他们支持它,但在 C99 中,正如 FAQ 所说,他们添加了 flexible array members, which I cover in this answer 6.7.2.1 Structure and union specifiers 部分中有介绍,并且有以下示例,与 C90 示例不同,它不需要特殊的数学运算来计算数组的大小:

EXAMPLE After the declaration:

struct s { int n; double d[]; };

the structure struct s has a flexible array member d. A typical way to use this
is:

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

and assuming that the call to malloc succeeds, the object pointed to by p
behaves, for most purposes, as if p had been declared as:

struct { int n; double d[m]; } *p;

(there are circumstances in which this equivalence is broken; in particular, the
offsets of member d might not be the same).

关于c - C90 中的可变长度结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23093220/

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