求高人指点
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
构体(struct)
简单来说,结构体的数据成员在内存中的顺序是确定的,但是每个数据成员前后有可能插入一定数量的位(bit)来保证内存是对齐的。如下图所示:
每个方格右上角的数字即变量的起始地址偏移量。
From C99 §6.7.2.1:
12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.
13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
联合体(union)
简单来说,联合体中的所有成员的地址都是相同的。如下图所示:
三个变量的起始地址偏移量都是 0。
From the C99 standard §6.7.2.1:
14 The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa.
参考
•C struct memory layout - Stack Overflow
•Memory layout of union of different sized member - Stack Overflow
•ELF ABI §3.1