一、前言
本文用来记录自己的学习过程,主要是C语言关键词typedef的学习。
typedef是c语言的关键字
作用是为一种数据类型定义一个新名字
这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)
和struct来匹配为了代码编写简洁和普通类型匹配,通过名字来获取信息
typedef和自定义结构体struct配合使用时, 常常进行另外命名的同时给出模板指针,更便于使用。
二、示例
#include <stdio.h>
#include <stdlib.h>
/*
typedef
typedef是c语言的关键字
作用是为一种数据类型定义一个新名字
这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)
和struct来匹配为了代码编写简洁
和普通类型匹配,通过名字来获取信息
*/
// 单片机开发中,寄存器为8、16、32位
typedef unsigned char u_int8;//(0 255)
typedef unsigned short int u_int16;
typedef unsigned int u_int32;
typedef struct Student
{
int score;
char *name;
}STU,*PSTU; //将自定义的结构体struct Student模板命名为STU 给出模板指针*PSTU
int main()
{
u_int8 data0 = 10;
u_int16 data1 = 11;
u_int32 data2 = 22;
printf("%d %d %d\n",data0,data1,data2);
//使用名称
STU stu;
stu.score=99;
printf("stu_score=%d\n",stu.score);
//使用指针
PSTU pstu;
pstu=(PSTU)malloc(sizeof(STU));
pstu->score=100;
printf("pstu_score=%d\n",pstu->score);
//使用指针但不用typedef
struct Student* pstu1;
pstu1=(struct Student *)malloc(sizeof(struct Student));
pstu1->score =88;
printf("pstu1_score=%d\n",pstu1->score);
system("pause");
return 0;
}