C 声明的目的是什么;int t[0]&引用;发球?

C 声明的目的是什么;int t[0]&引用;发球?,c,c99,C,C99,以下声明的目的是什么 struct test { int field1; int field2[0]; }; 这是一个零大小的数组,如果没有C99,它会很有用。这只是一个0长度的数组。根据: GNUC中允许使用零长度数组。作为 结构的最后一个元素,它实际上是 可变长度对象: 它是用于封装的 它用于在不知道任何细节的情况下创建接口。 下面是一个简单的例子 在test.h(接口)中,它显示了一个结构测试,它有两个字段。 它有三个功能,第一个是创建结构。 set_x是将一些整数存

以下声明的目的是什么

struct test
{
     int field1;
     int field2[0];
};

这是一个零大小的数组,如果没有C99,它会很有用。

这只是一个0长度的数组。根据:

GNUC中允许使用零长度数组。作为 结构的最后一个元素,它实际上是 可变长度对象:


它是用于封装的

它用于在不知道任何细节的情况下创建接口。 下面是一个简单的例子

在test.h(接口)中,它显示了一个结构测试,它有两个字段。 它有三个功能,第一个是创建结构。 set_x是将一些整数存储到结构中。 get_x是获取存储的整数

那么,我们什么时候可以存储x

负责实现(test.c)的人员将声明另一个包含x的结构。 并在“test_create”中使用一些技巧来malloc此结构

接口和实现完成后。 应用程序(main.c)可以在不知道x在哪里的情况下设置/获取x

测试h

struct test_t
{
    int field1;
    int field2[0];
};

struct test_t *test_create();
void set_x(struct test_t *thiz, int x);
int get_x(struct test_t *thiz);
测试c

#include "test.h"
struct test_priv_t {
    int x;
};

struct test_t *test_create()
{
    return (struct test_t*)malloc(sizeof(struct test_t) + sizeof(struct test_priv_t);
}


void set_x(struct test_t *thiz, int x)
{
    struct test_priv_t *priv = (struct test_priv_t *)thiz->field2;
}

int get_x(struct test_t *thiz)
{
    struct test_priv_t *priv = (struct test_priv_t *)thiz->field2;
}
main.c

#include "test.h"

int main()
{
    struct test_t *test = test_create();
    set_x(test, 1);
    printf("%d\n", get_x(test));
}

注意:如果可以使用C99,请使用
struct test{int field1;int field2[];}取而代之。这在所有C99(及更高版本)编译器中都是可移植的。为了给它添加一个可搜索的术语,这种野兽被称为“flexible array member”。我知道你是从GNU站点复制的,所以这不是你的错,但是
这个长度在任何地方都没有定义。@Hunter McMillen:这只是一个片段。无论如何,要编译代码,您必须添加更多的内容。我假设它只是要分配给
lengh
成员的某个值。
#include "test.h"

int main()
{
    struct test_t *test = test_create();
    set_x(test, 1);
    printf("%d\n", get_x(test));
}