Home > front end >  Dynamically allocate memory for an array of unions inside a struct
Dynamically allocate memory for an array of unions inside a struct

Time:10-07

I'm not sure that I'm approaching this correct, but what I'm trying to do is to dynamically allocate memory for the array of unions inside the struct, I could use

Registers regs[20];

But I don't want it to be fixed to 20*2 bytes. Instead I want something like this:

typedef union
    uint16_t reg;
    uint8_t low;
    uint8_t high;
}Registers;

typedef struct{
    uint8_t updateIntervall;  
    uint8_t prio;
    Registers *regs;         // <--- Array of unions 
}Config;


uint8_t amount = 4;
Config cfg;
cfg.regs = malloc((amount * 2) * sizeof(uint8_t));

And I guess that

Config cfg;

Already inits the struct, so this should not work.

I'm guessing that I'm doing it completely the wrong way, so if someone could point me in the right direction I would appreciate it.

CodePudding user response:

I would do it another way. nregs is the size of the array

typedef struct{
    uint8_t updateIntervall;  
    uint8_t prio;
    Registers regs[];         // <--- Array of unions 
}Config;

Config *cfg=malloc(sizeof(*cfg)   nregs * sizeof(cfg->regs[0]));
  • Related