使用可变长度数组成员分配结构体 [英] Allocating struct with variable length array member

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

问题描述

我知道我可以通过 new char [n] 创建一个 n chars的数组。即使 n 不是编译时常数,它也可以工作。

I know I can do new char[n] to create an array of n chars. This works even when n is not a compile time constant.

但是我想说的是, n chars:

But lets say I wanted a size variable followed by n chars:

我的第一次尝试如下:

struct Test
{
  std::size_t size;
  char a[];
};

但是看起来 new Test [n] 不按我的期望,而是分配 n size s。

However it seems new Test[n] doesn't do what I expect, and instead allocates n sizes.

我还发现 sizeof(std :: string)在ideone是4,所以似乎它可以分配大小和char数组在一个块。

I've also found that sizeof(std::string) is 4 at ideone, so it seems it can allocate both the size and the char array in one block.

有一种方式我可以实现我描述的(可能是 std :: string 是)?

Is there a way I can achieve what I described (presumably what std::string already does)?

推荐答案

虽然您可以执行此操作(并且它经常在C中用作排序的解决方法)不建议这样做。但是,如果这是真的你想做什么...这里是一个方法来做它与大多数编译器(包括那些不能很好地与C99增强功能)。

While you can do this (and it was often used in C as a workaround of sorts) it's not recommended to do so. However, if that's really what you want to do... here's a way to do it with most compilers (including those that don't play nicely with C99 enhancements).

#define TEST_SIZE(x) (sizeof(Test) + (sizeof(char) * ((x) - 1)))

typedef struct tagTest
{
    size_t size;
    char a[1];
} Test;

int elements = 10; // or however many elements you want
Test *myTest = (Test *)malloc(TEST_SIZE(elements));

C99之前的C规范不允许在结构中使用零长度数组。要解决这个问题,创建一个具有单个元素的数组,并将一个小于请求的元素数量的元素添加到实际结构的大小(大小和第一个元素),以创建预期大小。

The C specifications prior to C99 do not allow a zero-length array within a structure. To work around this, an array with a single element is created, and one less than the requested element count is added to the size of the actual structure (the size and the first element) to create the intended size.

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

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