复合类型
结构体
结构体:将多个相同或不同类型的数据存在在一块连续的内存空间中
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//定义一个结构体
//大括号内可以是任意类型,结尾注意记得分号
struct stu
{
int id;
int age;
char name[125];
}a, b; // 定义类型时同时定义了两个变量
struct stu c;
struct stu arr[20]; // 数组的每一个元素都是结构体, 用法一样
int main()
{
// 使用域操作
a.id = 1;
a.age = 20;
memcpy(a.name, "xiguan", 6);
printf("%d %d %s\n", a.id, a.age, a.name);
// 使用地址操作
(&b)->id = 2;
(&b)->age = 21;
memcpy((&b)->name, "jesses", 6);
printf("%d %d %s\n", (&b)->id, (&b)->age, (&b)->name);
return 0;
}
共用体
多个变量共用同一块内存空间"同一时刻,只能有一个变量起作用
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 定义共用体
union mi
{
char a;
short b;
int c;
};
int main()
{
union mi a;
a.a = '1';
printf("%c %d %d\n", a.a, a.b, a.c);
a.b = 2;
printf("%c %d %d\n", a.a, a.b, a.c);
a.c = 3;
printf("%c %d %d\n", a.a, a.b, a.c);
return 0;
}
枚举
将枚举类型的变量的值一一列举出来,枚举变量的值只可以赋值为{}里面的值,{里面的值是常量
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 枚举
enum tq {SUN, RAIN = 4, SLOW}; //从第一个后面递增, 如果赋值前面从0开始算
int main()
{
printf("%d %d %d\n", SUN, RAIN, SLOW);
return 0;
}
typedef
typedef是用来给类型取别名
typedef 原类型 新类型
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 枚举
enum tq {SUN, RAIN = 4, SLOW}; //从第一个后面递增, 如果赋值前面从0开始算
struct stt
{
int a;
int b;
};
typedef struct stt TT;
TT x1;
typedef struct stu
{
int a;
int b;
}stu;
stu x2;
int main()
{
printf("%d %d %d\n", SUN, RAIN, SLOW);
return 0;
}