简体   繁体   English

C Struct数组成员没有特定长度

[英]C Struct array member without specific length

I have encountered this piece of code: 我遇到过这段代码:

struct test                   
{                                        
 uint32       num_fields;            
 char array_field [];               
}; 

How can I understand array_field ? 我怎么能理解array_field Is this a gcc extension for the C language? 这是C语言的gcc扩展吗?

It's a C99 feature, called flexible array member which is typically used to create a variable length array. 它是一个C99功能,称为灵活数组成员 ,通常用于创建可变长度数组。

It can only be specified as the last member of a struct without specifying the size (as in array_field []; ). 它只能被指定为一个结构的最后一个成员,而无需指定尺寸(如在array_field [];


For example, you can do the following and the member arr will have 5 bytes allocated for it: 例如,您可以执行以下操作,并且成员arr将为其分配5个字节:

struct flexi_example
{
int data;
char arr[];
};


struct flexi_example *obj;

obj = malloc(sizeof (struct flexi_example) + 5);

Its pros/cons discussed here: 它的优点/缺点在这里讨论:

Flexible array members in C - bad? C中的灵活阵列成员 - 糟糕吗?

Such structures are usually allocated on the heap with a calculated size, with code such as the following: 此类结构通常在堆上以计算的大小分配,代码如下:

#include <stddef.h>

struct test * test_new(uint32 num_fields)
{
    size_t sizeBeforeArray = offsetof(struct test, array_field);
    size_t sizeOfArray = num_fields * sizeof(char);
    struct test * ret = malloc(sizeBeforeArray + sizeOfArray);
    if(NULL != ret)
    {
        ret->num_fields = num_fields;
    }
    return ret;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM