Mst137 Mst137 - 4 months ago 12
C Question

Varying the Size of a Structure?

I have created a structure called Register, with around 8 fields within it. I now want to create a structure called Instrument, which should have a variable amount of of fields, 6 which are the same for every instrument, plus a certain amount of fields depending on how many registers are attributed to it. How can I create this?

For clarity here is what I would like to create (although may not be accurate).

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

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

Answer

You can make use of flexible array members to achieve the same.

Something like

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

and then, you can allocate memory as needed to someVar.Reg later.

For an example, quoting C11, chapter ยง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;
Comments