C语言基础08--结构体

Catalogue
  1. 1. C语言基础08–结构体&联合体&枚举类型
    1. 1.0.1. 结构体的声明:
    2. 1.0.2. 结构体指针
    3. 1.0.3. 结构体参数
    4. 1.0.4. 联合体
    5. 1.0.5. 枚举类型

C语言基础08–结构体&联合体&枚举类型

结构体的声明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>
int main() {
struct NPC
{
char * Name;
int HP;
int MP;
};
struct NPC xiaoer;
xiaoer.Name = "xiaoer";
xiaoer.HP = 100;
xiaoer.MP = 200;

return 0;
}

结构体指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<stdio.h>
int main() {
struct NPC
{
char * Name;
int HP;
int MP;
};
struct NPC npcarr[100];
struct NPC *npcindex;//声明一个结构体指针
npcindex = &npcarr[0];
npcindex->Name = "xiao1";//通过指针可以修改内容
npcindex++;//指针每次移动一个结构体的量
npcindex->Name = "xiao222";

return 0;
}

结构体参数

在函数中的应用:作为参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<stdio.h>
struct NPC
{
char * Name;
int HP;
int MP;
};

int outputNPC(struct NPC a) {
printf("%s\nHP=%d\nMP=%d", a.Name, a.HP, a.MP);
return 0;
}

int initNPC(char * name, int HP, int MP) {
struct NPC npc1;
npc1.Name = name;
npc1.HP = HP;
npc1.MP = MP;
outputNPC(npc1);
return 0;
}

int main() {
initNPC("lihua", 10, 1000);

return 0;
}

联合体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "main.h"

union Info {
int HP;
char PlayerName;
};
int main() {
union Info Myinfo;
Myinfo.PlayerName = 'a';
//联合体所有成员地址都是一样的
Myinfo.HP = 1111;
//多个值初始化之后只显示最后一个值,也就是同时只能使用其中一个成员

printf("%c\n%d\n", Myinfo.PlayerName, Myinfo.HP);
return 0;
}

枚举类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "main.h"

int main() {
enum color {red,green,blue};//实际是个整数类型
int flag = 0;
scanf("%d", &flag);
switch (flag) {
case red:printf("red"); break;
case green:printf("freen"); break;
case blue:printf("blue"); break;
}
//用来看的更清晰
return 0;
}