gpt4 book ai didi

c - 无维数组字段,它的用途?

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:44 24 4
gpt4 key购买 nike

struct test{
unsigned long int asd[][3][6];
};

sizeof(struct test) 返回 0。因此,如果这是

的确切别名
struct test{
unsigned long int asd[0][3][6];
};

这样的字段声明有实际用途吗?您可能还会考虑模板元编程的东西,这总是令人惊讶。

最佳答案

第一个示例演示了灵活数组成员 的使用,这是 C99 的一个特性。然而,为了让该片段能够编译,您需要在您的 struct 中有另一个成员,即:

struct test{
int a;
unsigned long int asd[][3][6];
};

This documentation在 gcc 上告诉你为什么 sizeof 求值为零,以及普通数组的语法差异:

In ISO C90, you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.

In ISO C99, you would use a flexible array member, which is slightly different in syntax and semantics:

  • Flexible array members are written as contents[] without the 0.
  • Flexible array members have incomplete type, and so the sizeof operator may not be applied. As a quirk of the original implementation of zero-length arrays, sizeof evaluates to zero.
  • Flexible array members may only appear as the last member of a struct that is otherwise non-empty.
  • A structure containing a flexible array member, or a union containing such a structure (possibly recursively), may not be a member of a structure or an element of an array. (However, these uses are permitted by GCC as extensions.)

关于c - 无维数组字段,它的用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705860/

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