结构体类型T [1]中的最后一个成员,而不是T * [英] Last member in structs type T[1] instead of T*

查看:180
本文介绍了结构体类型T [1]中的最后一个成员,而不是T *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到我的项目中的下一个代码:

I saw next code in the project I work:

struct Str
{
    size_t count;
    T data[1];
};

Str* str = (Str*)malloc(sizeof(Str) + sizeof(T) * count);
str->count = count
...

str-> data 用作 count 的元素 T

为什么要声明 T data [1] 而不是 T * data ?这是否有什么好处?

Why one would declare T data[1] instead of T* data? Is there any benefit of doing this?

推荐答案

您的代码无效C ++。

Your code is not valid C++.

但是,它是有效的C,排序。在C中写这个的标准方法是声明最终成员为 T data []; (一个柔性长度数组),目的是允许你请分配一个单一的动态内存块,并将一个固定的头和一个可变长度数组存储在一起。

However, it is valid C, sort of. The standard way of writing this in C is to declare the final member as T data[]; (a "flexible-length array"), and the purpose is to allow you do allocate one single dynamic chunk of memory and store both a fixed header and a variable-length array in it together.

使用这种类型有几个限制它不能是自动变量的类型或数组元素的类型)。例如,请参见 GCC实施,其中提供了几个非标准扩展。

There are several limitations to using such a type (e.g. it cannot be the type of an automatic variable, or of an array element). See for example the GCC implementation, which offers several non-standard extensions.

这篇关于结构体类型T [1]中的最后一个成员,而不是T *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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