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

标签 c

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/

相关文章:

c - 结构和 union :从性能的角度来看哪个更好?通过值或指针传递参数?

c - 指针和数组的微妙概念

c - 如何使用文件扩展名的访问方法?

c - C中链表声明的区别

c - 共享 pthread_cond_broadcast 卡在 futex_wait

c - glob 的结果是如何排序的?

c - 右箭头等于右箭头

c - 使用cJSON读取JSON数组元素的问题

连续可变有序列表

c - 在 C 语言中,调用者是否曾经特别对待可变参数?