Search code examples
cdynamic-memory-allocation

Dynamically allocate memory for an array of unions inside a struct


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.


Solution

  • 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]));