1.4 数据结构与算法预备知识之——typedef的用法

为什么需要 typedef

在遇到一些自己定义的结构体啊这种名字很长的自定义变量类型时(系统定义变量类型也一样),可以利用这个 typedef() 去给它多起一个别名来简化,避免一直进行很复杂的名字的输入

怎么使用 typedef

方法一:在前面加一个声明

#include <stdio.h>
#include <string.h>

typedef struct Student ST;

struct Student
{
	int sid;
	char name[100];
	int age;
	char sex[100];
};

int main()
{
	ST st;
	st.sid = 201503010;
	strcpy_s(st.sex, "male");
	st.age = 23;
	strcpy_s(st.name, "June");
	printf("%d %s %d %s", st.sid, st.name, st.age, st.sex);
	return 0;
}

201503010 June 23 male

方法二:定义结构体时直接使用

#include <stdio.h>
#include <string.h>

typedef struct Student
{
	int sid;
	char name[100];
	int age;
	char sex[100];
}ST;

int main()
{
	ST st;
	st.sid = 201503010;
	strcpy_s(st.sex, "male");
	st.age = 23;
	strcpy_s(st.name, "June");
	printf("%d %s %d %s", st.sid, st.name, st.age, st.sex);
	return 0;
}

201503010 June 23 male

方法三:利用这个来直接重命名这个类型的指针

#include <stdio.h>

typedef struct Student
{
	int sid;
	char name[100];
	int age;
	char sex[100];
} * PST;    // 等价于直接跳了一步定义出来一个struct Student *类型的数据类型

int main()
{
	struct Student st;
	PST ps = &st;
	ps->sid = 201905;
	printf("%d", ps->sid);
	return 0;
}

201905

方法四:更进一步,既重命名那个类型,又重命名那个类型的指针

#include <stdio.h>

typedef struct Student
{
	int sid;
	char name[100];
	int age;
	char sex[100];
} *PST, ST;    // 定义一个struct Student *类型的数据类型PST和struct Student类型的数据类型ST

int main()
{
	ST st;         // 等价于 struct Student st
	PST ps = &st;  // 等价于 struct Student * ps = &st
	ps->sid = 201905;
	printf("%d", ps->sid);
	return 0;
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值