9.构造数据类型
struct 结构体名
{
数据类型 成员变量1;
数据类型 成员变量2;
数据类型 成员变量3;
};
struct date
{
int year;
int moon;
int day;
};
2.结构体变量的定义
数据类型 变量名;
struct student a;
#include<stdio.h>
struct time
{
int year;
int mon;
int day;
};
int main(void)
{
struct time a;
return 0;
}
3.结构体变量的初始化
1.全部初始化
struct student a = {"zhangsan",'m',17,90}
struct book b = {"C语言","Dennis Ritchie,{1987,1,1}}
struct datetime dt = {{2026,1,22},{14,18,30}}
#include<stdio.h>
struct time
{
int year;
int mon;
int day;
};
int main(void)
{
struct time a = {2026,1,22};
return 0;
}
2.局部初始化
例如:struct student a = { .name = {"zhangsan"}, .score = 100, }; struct datetime dt = { .d = { .year = 2026, }, .t = { .hour = 14, .min = 20, }, };
#include<stdio.h>
struct time
{
int year;
int mon;
int day;
};
int main(void)
{
struct time a = {
.year = 2026,
.mon = 1,
.day = 22,
};
return 0;
}
4.结构体成员变量的访问
1.结构体变量类型访问成员变量用.
2.结构体指针类型访问成员变量用->
3.无论用结构体变量访问成员变量还是结构体指针访问成员变量,由成员变量的类型决定。
1 #include<stdio.h>
2 struct date
3 {
4 int year;
5 int moon;
6 int day;
7 };
8 struct time
9 {
10 int hour;
11 int min;
12 int sec;
13 };
14 struct student
15 {
16 char name [32];
17 char sex [32];
18 int age;
19 int score;
20 };
21 struct datetime
22 {
23 struct date d;
24 struct time t;
25 };
26 struct book
27 {
28 char book_name[32];
29 char writer[32];
30 int public_day;
31 int public_moon;
32 int public_year;
33 };
34 int main(void)
35 {
36 struct date a = {2026,1,22};
37 struct time b = {14,39,27};
38 struct student c = {"张三","男",17,89};
39 printf("姓名:%s\\n",c.name);
40 printf("性别:%s\\n",c.sex);
41 printf("年龄:%d\\n",c.age);
42 printf("成绩:%d\\n",c.score);
43 printf("%04d-%02d-%02d %02d:%02d:%02d\\n",a.year,a.moon,a.day,b.hour,b.min,b.sec);
44
45 return 0;
46 }
~
1 #include<stdio.h>
2
3 struct student
4 {
5 char name[32];
6 char sex[32];
7 int age;
8 int score;
9 };
10 void getstudent(struct student *p)
11 {
12 scanf("%s",p->name);
13 scanf("%s",p->sex);
14 scanf("%d",&p->age);
15 scanf("%d",&p->score);
16
17 return ;
18 }
19 void printfstudent(struct student *p)
20 {
21 printf("名字:%s\\n",p->name);
22 printf("性别:%s\\n",p->sex);
23 printf("年龄:%d\\n",p->age);
24 printf("成绩:%d\\n",p->score);
25 return;
26 }
27 int main(void)
28 {
29
30 struct student d = {0};
31 getstudent(&d);
32 printfstudent(&d);
33 return 0;
34 }
~

5.结构体的存储
1.内存对齐:
- 结构体成员变量只能存放在内存地址为自身基本类型长度整数倍的内存单元中。
- 结构体的大小必须为最大基本类型长度的整数倍。
6.结构体作为函数参数
struct date fun(void);
void fun(struct date day);
void fun(struct date *pday);






