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 常见问题解答包含在 Question 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 */

尽管常见问题解答确实说:



尽管 gcc 文档基本上说他们支持它,但在 C99 中,正如 FAQ 所说,他们添加了 flexible array members, which I cover in this answer,在 6.7.2.1 结构和 union 说明符一节中介绍,并具有以下示例,与 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/

10-11 06:58