gpt4 book ai didi

c - 带有大括号初始化的灵活数组成员的大小

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:25 24 4
gpt4 key购买 nike

假设我有这段代码:

const struct
{
const char * const name;
const unsigned length;
const char data[951357];
} var[] =
{
{
"dataset1",
#include "dataset1.h"
},
{
"dataset2",
#include "dataset2.h"
},
/* ... */
};

每个 dataset*.h 包含如下内容:

6,
{
0x04, 0x08, 0x15, 0x16, 0x23, 0x42
}

这需要我提前知道最大数据集的大小。这不是面向 future 的,因为添加数据集的任何人还必须检查并可能修改 data 的大小,并且可能导致严重的内存浪费(在我的真实情况下,已经有~15 个数据集,大小在数百 KB 之间)

有什么解决办法吗?

唯一的硬性要求是每个数据都必须在自己的文件中,但该文件的格式可以是任何格式。我还希望尽可能将所有内容都保持为 const

编辑:我应该提到旧代码是这样做的:

struct dataset { char* name; int length; char* data; };
struct dataset *alldata[10];
struct dataset dataset1 = {
"dataset1",
#include "dataset1.h"
};
/* same again for every dataset */
int main()
{
alldata[0] = malloc(sizeof(struct dataset));
memcpy(alldata[0], dataset1, sizeof(struct dataset));
/* again, block copied for each dataset */
}

该代码在我看来很难看,并且需要(我认为)不必要的内存副本。重写该代码时,我的目标是让它在编译时存储所有数据,然后仅在运行时必要时读取。

最佳答案

您可以使用指向数据的指针。您为额外的指针付出了代价,但考虑到数据的大小,没有太大的数组可以节省很多。

#include "dataset1.h"
/* other dataset includes here */
struct DataSet {
const char * name;
unsigned length;
const char * data;
};
const struct DataSet var[] = {
{
"dataset1",
dataset1_length,
dataset1_data,
},
/* other dataset inits here */
};

dataset1.h

enum { dataset1_length = 6 };
extern const char dataset1_data[];

dataset1.c

const char dataset1_data[] = { 0x04, 0x08, 0x15, 0x16, 0x23, 0x42 };

请注意我是如何删除不必要的 const 的,但所有数据仍然是 const

如果不需要额外的编译单元,只需将​​头文件和源文件合并为一个头文件并直接包含:

dataset1.h

enum { dataset1_length = 6 };
const char dataset1_data[] = { 0x04, 0x08, 0x15, 0x16, 0x23, 0x42 };

关于c - 带有大括号初始化的灵活数组成员的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35551216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com