是否可以创建可以转换为可变大小缓冲区的结构?例如,如果我有一些看起来像这样的数据:
0 1 2 3 4 5 6 7 8
+--+--+--+--+--+--+--+--+
| |
/ /
/ DATA /
| |
+--+--+--+--+--+--+--+--+
| NAME |
+--+--+--+--+--+--+--+--+
| TIME |
+--+--+--+--+--+--+--+--+
| ETC |
+--+--+--+--+--+--+--+--+
有没有可能有一个类似这样的结构
typedef struct{
uint8_t data[];
uint8_t name;
uint8_t time;
uint8_t etc;
}Struct;
然后在运行时调整 Struct.data 的大小,以便我可以将结构直接转换到缓冲区?
我知道我可以创建一个使用指针的结构并让它们指向缓冲区的一部分,但我很好奇这是否可行,因为它会简化我的代码并使其更易于阅读/使用。
最佳答案
听起来您正在尝试执行以下操作:
typedef struct {
uint8_t name;
uint8_t time;
uint8_t etc;
} Struct;
char *buf = ...;
Struct *s = (Struct*)(buf + data_len);
... s->name ...
这有两个问题。
- 对齐。您不能只在每台机器上的任何地址放置一个结构,所以这个概念从根本上是有缺陷的,除非您也针对特定的机器。
- 填充。编译器可以自由地在结构的字段之间放置填充,因此这个概念从根本上是有缺陷的,除非您针对特定的编译器并告诉该编译器不要使用任何填充。
简而言之,采取不同的方法。
typedef struct {
uint8_t name;
uint8_t time;
uint8_t etc;
} Struct;
char *buf = ...;
buf += data_len;
Struct s;
memcpy(&s.name, buf, sizeof(s.name)); buf += sizeof(s.name);
memcpy(&s.time, buf, sizeof(s.time)); buf += sizeof(s.time);
memcpy(&s.etc, buf, sizeof(s.etc)); buf += sizeof(s.etc);
... s.name ...
检查以确保您没有读取超出 buf
结尾的部分留给您。
关于将结构转换为可变长度缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65056058/