簡體   English   中英

為結構內的聯合數組動態分配 memory

[英]Dynamically allocate memory for an array of unions inside a struct

我不確定我是否正在接近這個正確的方法,但我想做的是為結構內的聯合數組動態分配 memory,我可以使用

Registers regs[20];

但是我不希望它被固定為 20*2 字節。 相反,我想要這樣的東西:

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

我猜

Config cfg;

已經初始化結構,所以這不應該工作。

我猜我做的方式完全錯誤,所以如果有人能指出我正確的方向,我將不勝感激。

我會用另一種方式來做。 nregs是數組的大小

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM