【发布时间】:2020-09-01 18:40:06
【问题描述】:
让我们看看下面的structs:
struct child {
int a:1;
int b:2;
int c:2;
} __attribute__((packed));
struct parent1 {
int x:3;
struct child y;
} __attribute__((packed));
struct parent2 {
int p:1;
int q:5;
int r:5;
struct child s;
} __attribute__((packed));
这些是我得到的尺寸:
sizeof(int) 4
sizeof(struct child) 1
sizeof(struct parent1) 2
sizeof(struct parent2) 3
我听说出于性能原因在结构之前添加了填充。 但是暂时忘记了性能, 有没有办法让我得到以下尺寸?
sizeof(struct parent1) 1
sizeof(struct parent2) 2
实际上只需要这么多内存...
编辑
在linux 上使用gcc 有什么办法吗?
【问题讨论】:
-
这能回答你的问题吗? Size of structure with bit fields
-
不,你不能。
struct child不能小于1。 -
然后接受它给你的尺寸。你记忆力不够吗?
-
你几乎可以用 C 做任何事情,只是有时它会变得丑陋、不可移植或笨拙。
标签: c memory struct bit-fields