gpt4 book ai didi

c - 改变结构的大小?

转载 作者:行者123 更新时间:2023-12-01 22:23:07 25 4
gpt4 key购买 nike

我创建了一个名为 Register 的结构,其中包含大约 8 个字段。我现在想创建一个名为 Instrument 的结构,它应该有可变数量的字段,6 个对于每个仪器都是相同的,加上一定数量的字段,具体取决于有多少寄存器归因于它。我怎样才能创建这个?

为了清楚起见,这里是我想要创建的内容(尽管可能不准确)。

    typedef struct {
int x;
int y;
int z;
} Register;

typedef struct {
int x;
int y;
int z;
Register Reg1;
Register Reg2;
...
} Instrument;

最佳答案

您可以使用 flexible array members实现相同的目标。

有点像

typedef struct {
int x;
int y;
int z;
Register Reg1;
Register Reg2; //upto this is fixed....
Register Reg[];
} Instrument;

然后,您可以根据需要为 someVar.Reg 稍后分配内存。

举个例子,引用C11,章节§6.7.2.1/20

EXAMPLE 2 After the declaration:

   struct s { int n; double d[]; };

the structure struct s has a flexible array member d. A typical way to use this is:

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

and assuming that the call to malloc succeeds, the object pointed to by p behaves, for most purposes, as if p had been declared as:

struct { int n; double d[m]; } *p;

关于c - 改变结构的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38770073/

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