[英]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我不确定我是否正在接近这个正确的方法,但我想做的是为结构内的联合数组动态分配 memory,我可以使用
Registers regs[20];
But I don't want it to be fixed to 20*2 bytes.但是我不希望它被固定为 20*2 字节。 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.我猜我做的方式完全错误,所以如果有人能指出我正确的方向,我将不胜感激。
I would do it another way.我会用另一种方式来做。
nregs
is the size of the array 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.