C语言-结构体
结构体声明
#include <stido.h>
struct People
{
char name
[10];
int age
;
unsigned int birthday
;
char address
[40];
float social_status
;
};
定义结构体关键字 struct 结构体需要以 ; 结尾
定义结构体
int main
(void)
{
struct People people
;
}
或在声明时定义:
#include <stido.h>
struct People
{
char name
[10];
int age
;
unsigned int birthday
;
char address
[40];
float social_status
;
} people
;
初始化一个结构体变量
struct People people
=
{
"张无忌",
18,
19980807,
"少林寺驻武当山办事处",
999.88
};
引用结构体变量成员
int main
(void)
{
struct People people
;
printf("请输入姓名: ");
scanf("%s", people
.name
);
printf("请输入年龄: ");
scanf("%d", &people
.age
);
printf("请输入生日: ");
scanf("%d", &people
.birthday
);
printf("请输入住址: ");
scanf("%s", people
.address
);
printf("请输入身价: ");
scanf("%f", &people
.social_status
);
printf("\n============人员信息录入完毕===============\n");
printf("姓名: %s\n", people
.name
);
printf("年龄: %d\n", people
.age
);
printf("生日: %d\n", people
.birthday
);
printf("住址: %s\n", people
.address
);
printf("身价: %.2f\n", people
.social_status
);
return 0;
}
内存对齐
*为使cup对数据读取/处理的速度更快, 编译器对结构体的成员进行内存对齐。
#include <stido.h>
struct S
{
char a
;
int b
;
char c
;
};
int main
(void)
{
struct S s
= {'x', 520, 'o'};
printf("size of s = %ld\n", sizeof(s
));
}
一个char类型占1个字节,一个int类型占4个字节, 所以我们预判结果为 6(1+4+1)。但实际结果却为12, 这是为什么呢? 是因为:
对齐前:
abc
一个字节 四 个 字 节 一个字节
对齐后:
a b c
一个字节 四 个 字 节 一个字节
(一般操作系统的对齐参数为4, a、c 后均由三个字节填充)
将上述结构体调整:
struct S2
{
char a
;
char c
;
int b
;
};
int main
(void)
{
struct S2 s2
= {'x', 'o', 520};
printf("size of s2 = %ld\n", sizeof(s2
));
}
对齐后:
acb
一个字节一个字节 四 个 字 节
所以, 可以通过调整结构体成员的顺序, 来节省内存空间。