改变结构的大小?

Varying the Size of a Structure?

我创建了一个名为 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;

你可以使用指针

typedef struct 
{
   int    x;
   int    y;
   int    z;
   Register *reg;
} Instrument;

在代码中使用它

Instrument a.reg = malloc(sizeof(Register)*NUM_OF_REGISTERS);
if (a.reg != NULL)
{
   // your STUFF
   free(a.Reg);
}