7

char fl[1]我查看了几个实例,其中我在以下代码片段中看到了类似的内容。我无法猜测这种结构的用途可能是什么。

struct test
{
    int i;
    double j;
    char fl[1];
};

int main(int argc, char *argv[])
{
    struct test a,b;
    a.i=1;
    a.j=12;
    a.fl[0]='c';

    b.i=2;
    b.j=24;
    memcpy(&(b.fl), "test1" , 6);
    printf("%lu %lu\n", sizeof(a), sizeof(b));
    printf("%s\n%s\n",a.fl,b.fl);
    return 0;
}

输出 -

24 24 
c<some junk characters here>
test1
4

3 回答 3

7

它被称为“结构黑客”,您可以在C 常见问题解答中了解它。一般的想法是,您为列出的结构分配更多的内存,然后在最后使用数组,就好像它的长度大于 1。

不过,无需再使用此 hack,因为它已被 C99+灵活数组成员取代。

于 2013-01-30T16:46:02.720 回答
0

这个想法通常是为可变大小的数据命名,例如从套接字读取的数据包:

struct message {
    uint16_t len; /* tells length of the message */
    uint16_t type; /* tells type of the message */
    char payload[1]; /* placeholder for message data */
};

然后将缓冲区转换为此类struct,并通过索引数组成员来处理数据。

于 2013-01-30T16:49:52.373 回答
0

请注意,您编写的代码正在覆盖您不应该触摸的内存。将memcpy()多个字符写入一个字符数组。

这个用例通常更像这样:

struct test *obj;
obj = malloc(sizeof(struct test) + 300); // 300 characters of space in the
                                         // flexible member (the array).
obj->i = 3;
obj->j = 300;
snprintf(obj->f, 300, "hello!");
于 2013-01-30T16:51:18.787 回答