第九章 结构体
构体就是用户自定义数据类型。
结构体一般格式
struct
1.
struct 结构体名称{
成员列表;
};
注意:结构体后加 ;
// 2020/11/16
// C
#include <stdio.h>
#include <string.h>
//学生类型:学号,姓名,性别m,f
struct Student {
int id;
char name[20];
char sex;
};
int main() {
struct Student stu_1; // int a;
stu_1.id = 12;
strcpy(stu_1.name, "liangyuxuan");
stu_1.sex = 'M';
printf("name:%s,id=%d,sex=%c\n", stu_1.name, stu_1.id, stu_1.sex);
struct Student stu_2; // int a;
stu_2.id = 13;
strcpy(stu_2.name, "liangpi");
stu_2.sex = 'F';
printf("name:%s,id=%d,sex=%c\n", stu_2.name, stu_2.id, stu_2.sex);
return 0;
}
2.
struct 结构体名称{
成员列表;
}变量名称;
// 2020/11/16
// C
#include <stdio.h>
//学生类型:学号,姓名,性别m,f
struct Student {
int id;
char name[20];
char sex;
} stu_3 = {12, "liangpi", 'F'};
int main() {
printf("name:%s,id=%d,sex=%c\n", stu_3.name, stu_3.id, stu_3.sex);
return 0;
}
struct {
成员列表;
}变量名称;
// 2020/11/16
// C
#include <stdio.h>
//学生类型:学号,姓名,性别m,f
struct {
int id;
char name[20];
char sex;
} stu_4 = {12, "liangpi", 'F'};
int main() {
printf("name:%s,id=%d,sex=%c\n", stu_4.name, stu_4.id, stu_4.sex);
return 0;
}
结构体数组
// 2020/11/16
// C
#include <stdio.h>
//学生类型:学号,姓名,性别m,f
struct Student {
int id;
char name[20];
char sex;
};
int main() {
struct Student stu[5] = {
{12, "bob", 'M'}, {13, "lily", 'F'}, {14, "mike", 'M'},
{15, "liang", 'F'}, {16, "wang", 'M'},
};
for (int i = 0; i <= sizeof(stu)-sizeof(Student)-1; i++) {
printf("name:%s,id=%d,sex=%c\n", stu[i].name, stu[i].id, stu[i].sex);
}
return 0;
}
typedef取别名
// 2020/11/16
// C
// typedef 取别名
#include <stdio.h>
typedef int dog;
int main() {
dog a;
a = 1;
printf("%d\n", a);
return 0;
}
// 2020/11/16
// C
// typedef 取别名
#include <stdio.h>
#include <string.h>
typedef int dog;
typedef struct Student {
int id;
char name[20];
char sex;
} Stu;
int main() {
Stu stu_1;
stu_1.id = 12;
strcpy(stu_1.name, "liangyuxuan");
stu_1.sex = 'M';
printf("name:%s,id=%d,sex=%c\n", stu_1.name, stu_1.id, stu_1.sex);
return 0;
}
结构体指针
// 2020/11/16
// C
// 结构体指针
#include <stdio.h>
#include <string.h>
typedef struct Student {
int id;
char name[20];
char sex;
} Stu;
int main() {
Stu stu_1;
Stu *p;
p = &stu_1;
stu_1.id = 12;
strcpy(stu_1.name, "liangyuxuan");
stu_1.sex = 'M';
printf("常规:name:%s,id=%d,sex=%c\n", stu_1.name, stu_1.id, stu_1.sex);
printf("指针:name:%s,id=%d,sex=%c\n", (*p).name, (*p).id, (*p).sex);
printf("指向:name:%s,id=%d,sex=%c\n", p->name, p->id, p->sex);
return 0;
}