[英]Padding of a struct in C with 3 bytes
Let's say I have a struct and variables in C like this:假设我在 C 中有一个结构和变量,如下所示:
typedef struct {
uint8_t x;
uint8_t y;
uint8_t z;
}my_type;
my_type a;
my_type a10[10];
With C99 is it certain that使用 C99 是否可以确定
sizeof(a) == 3
? sizeof(a) == 3
? (and not 4 or 8) sizeof(a10) == 30
? sizeof(a10) == 30
? (and not 40 or 80) With C99 is it certain that
sizeof(a) == 3?
使用 C99 确定
sizeof(a) == 3?
This type will be used as color for an RGB888 framebuffer.
此类型将用作 RGB888 帧缓冲区的颜色。 So it's important to NOT have space between the adjacent RGB values.
所以在相邻的 RGB 值之间不要有空格是很重要的。
typedef struct {
uint8_t x;
uint8_t y;
uint8_t z;
}my_type;
No. The size may be 3 or 4 (or theoretically others, but not likely)不。大小可能是 3 或 4(或理论上其他,但不太可能)
2 solutions: 2个解决方案:
Give up portability and use compiler specif code to pack the structure.放弃可移植性并使用编译器特定代码来打包结构。
Change struct
to an array of 3 uint8_t
and adjust code.将
struct
更改为 3 uint8_t
的数组并调整代码。
I recommend the last.我推荐最后一个。
As mentioned in the comments, padding could be added by default.如评论中所述,默认情况下可以添加填充。
To avoid that you could use __attribute__((packed))
for your struct.为避免这种情况,您可以将
__attribute__((packed))
用于您的结构。
This will tell the compiler to pack your struct as tight as possible.这将告诉编译器尽可能紧凑地打包您的结构。
Would look like this:看起来像这样:
typedef struct {
uint8_t x;
uint8_t y;
uint8_t z;
} __attribute__((packed)) my_type;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.