4

以下声明的目的是什么?

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

3 回答 3

7

这只是一个长度为 0 的数组。根据http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

GNU C 允许使用零长度数组。它们作为结构的最后一个元素非常有用,它实际上是可变长度对象的标头:

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

 struct line *thisline = (struct line *)
 malloc (sizeof (struct line) + this_length);
 thisline->length = this_length;
于 2012-06-05T12:17:46.447 回答
3

它是一个大小为零的数组,如果您没有 C99 ,它是一个有用的GCC 扩展。

于 2012-06-05T12:16:49.110 回答
0

是为了封装。

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

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

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

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

一旦接口和实现已经完成。应用程序 (main.c) 可以在不知道它在哪里的情况下设置/获取 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;
}

主程序

#include "test.h"

int main()
{
    struct test_t *test = test_create();
    set_x(test, 1);
    printf("%d\n", get_x(test));
}
于 2012-06-05T13:19:05.213 回答