0
点赞
收藏
分享

微信扫一扫

【C语言自定义类型1】有趣的结构体1

结构体的创建与使用

比如我们打游戏时需要创建一个角色,首先需要定义一个结构体

【C语言自定义类型1】有趣的结构体1_结构体

struct hero
{
char name[20];//名字
int age;//年龄
char sex[20];//性别
int hp;//血量
int mp;//蓝量
};

当我们需要使用的时候

struct hero one={"alex",20,"武装直升机",100,100};

当你需要修改的时候

#define _CRT_SECURE_NO_WARNINGS 1
#include <string.h>
struct hero
{
char name[20];//名字
int age;//年龄
char sex[20];//性别
int hp;//血量
int mp;//蓝量
};
int main()
{
struct hero one = { "alex",20,"武装直升机",100,100};
struct hero* pt = &one;
pt->age = 21;
strcpy(pt->sex, "战斗机");
return 0;
}

注意一个汉字占两个字节

特殊声明

在声明结构的时候,可以不完全的声明。

//匿名结构体类型
struct
{
int a;
char b;
float c;
}x;
struct
{
int a;
char b;
float c;
}a[20], *p;

上面的两个结构在声明的时候省略掉了结构体标签

注意如果是这种情况p=&x是非法的因为编译器会将上面两个类型当作完全不相同的两个类型。

结构体的自引用

错误的方式

struct Node
{
int data;
struct Node next;
};

正确的方式

struct Node
{
int data;
struct Node* next;
};

typedef的使用

我们知道typedef可以对一个类型新声明一个定义

比如

typedef unsigned int uint;

结构体类型在创建时需要写一个struct为了简洁,我们可以在创建一个结构体类型时可一个直接使用一个typedef

typedef struct hero
{
char name[20];//名字
int age;//年龄
char sex[20];//性别
int hp;//血量
int mp;//蓝量
}hero;
int main()
{
hero one = { "alex",20,"武装直升机",100,100};
hero* pt = &one;
pt->age = 21;
strcpy(pt->sex, "战斗机");
return 0;
}

举报

相关推荐

0 条评论