Dou*_* II 10 c struct memory-management
在尝试为未来的C程序创建内存管理器时,我遇到了这个问题:
例如,考虑以下结构.
typedef struct {
int field1;
int field2;
char field3;
} SomeType;
Run Code Online (Sandbox Code Playgroud)
分配时,字段的内存地址是否在字段field1,field2,field3中?或者这不保证?
her*_*tao 27
简短的回答:它们被分配了在结构中声明的顺序.
示例:
#include <stdio.h>
#include <string.h>
struct student
{
int id1;
int id2;
char a;
char b;
float percentage;
};
int main()
{
int i;
struct student record1 = {1, 2, 'A', 'B', 90.5};
printf("size of structure in bytes : %d\n",
sizeof(record1));
printf("\nAddress of id1 = %u", &record1.id1 );
printf("\nAddress of id2 = %u", &record1.id2 );
printf("\nAddress of a = %u", &record1.a );
printf("\nAddress of b = %u", &record1.b );
printf("\nAddress of percentage = %u",&record1.percentage);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
size of structure in bytes : 16
Address of id1 = 675376768
Address of id2 = 675376772
Address of a = 675376776
Address of b = 675376777
Address of percentage = 675376780
Run Code Online (Sandbox Code Playgroud)
以下给出了上述结构存储器分配的图形表示.此图将帮助您非常轻松地理解C中的内存分配概念.

进一步阅读:请查看此处(也是上述示例的来源)for C – Structure Padding和Structure dynamic memory allocation in C.
你保证field3会在之后field2发生field1,并且field1在内存的开始处(即之前没有填充field1).但是,它们可能在其他成员之间填充(甚至之后field3).简而言之,声明它们的顺序是它们在内存中的排列顺序,尽管精确对齐和填充是实现定义的(但在第一个成员之前不会有任何填充).