【发布时间】:2021-11-27 08:31:21
【问题描述】:
我不确定我是否接近这个正确,但我想要做的是为结构内的联合数组动态分配内存,我可以使用
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;
已经初始化了结构,所以这应该不起作用。
我猜我的做法完全错误,所以如果有人能指出我正确的方向,我将不胜感激。
【问题讨论】:
-
您要分配
amount寄存器。因此它应该是malloc((amount * sizeof(Registers))或更好的malloc((amount * sizeof(*cfg.regs))。它在结构中的事实是无关紧要的 -
uint8_t low; uint8_t high;在联合中很奇怪。我想你的意思是union { uint16_t reg; struct { uint8_t low, hight; }} -
@Jabberwocky 为什么
malloc((amount * sizeof(*cfg.regs))比malloc((amount * sizeof(Registers))好?能否给我一个链接来解释这种差异? -
对于
x = malloc(amount * sizeof(*x)),我们只讨论x和amount。对于x = malloc(amount * sizeof(struct somestruct)),您需要确定x实际上是指向struct somestruct的指针。没有什么能阻止你写x = malloc(amount * sizeof(struct someotherstruct))。第一个版本不易出错。 -
@Jabberwocky 哦,现在我明白了。谢谢。
标签: c dynamic-memory-allocation