没有具体的长度C结构数组成员 [英] C Struct array member without specific length

查看:74
本文介绍了没有具体的长度C结构数组成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也遇到过这样code:

I have encounter such code:

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

如何理解array_field?这是C语言的一个gcc的扩展?

How to understand array_field? Is this a gcc extension for C language?

推荐答案

这是一个C99的功能,名为灵活的数组成员的这通常是用来创建一个可变长度的数组。

It's a C99 feature, called flexible array member which is typically used to create a variable length array.

它只能被指定为最后一个成员的结构的没有(在 array_field []作为; )指定的大小。

It can only be specified as the last member of a struct without specifying the size (as in array_field [];).

例如,你可以做以下和成员改编将已分配给它的5个字节:

For example, you can do the following and the member arr will have 5 bytes allocated for it:

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


struct flexi_example *obj;

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

它的优点/缺点这里讨论:

Its pros/cons discussed here:

用C灵活的数组成员 - 坏

Flexible array members in C - bad?

这篇关于没有具体的长度C结构数组成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆