typedef为C语言的关键字,作用是为一种数据类型定义一个新名字。这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)。
使用typedef目的一般有两个,一个是给变量一个容易记并且意义明确的新名字,另一个是简化一些比较复杂的类声明。
在单片机开发中需要配置一些寄存器,(8位、16位、32位),在这里typedef可以简化名字。
比如
typedef unsigned char u_int8; //8位无符号数
typedef unsigned short int u_int16; //16位无符号数
typedef unsigned int u_int32; //32位无符号数
unsigned表示无符号,那么unsigned char 就表示无符号的字符型,范围为(0 - 255),typedef的作用就是将 unsigned char定义为u_int8,使名字简化,
如果要访问这些变量的话,就可以用定义后的名字访问了
#include<stdio.h>
#include<stdlib.h>
int main()
{
typedef unsigned char u_int8;
typedef unsigned short int u_int16;
typedef unsigned int u_int32;
u_int8 data1 = 10; //相当于用u_int8代替了unsigned char
u_int16 data2 = 20;
u_int32 data3 = 30;
printf("%d %d %d\n",data1,data2,data3);
system("pause");
return 0;
}
typedef和结构体的配合使用
先看代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Student
{
int score;
char *name;
}STU;
int main()
{
STU data;
data.score = 100;
data.name = (char*)malloc(128);
memset(data.name,'\0',128);
data.name = "小明";
printf("名字是:%s\n分数是%d\n",data.name,data.score);
system("pause");
return 0;
}
其实这里typedef也相当于给结构体定义了一个新的名字,STU就是结构体struct Student的新名字,简化了结构体名字,定义结构体变量直接就是STU data,STU就代替了struct Student,访问也是一样的。
对于结构体指针也是一样的
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Student
{
int score;
char *name;
}STU,*PSTU; // PSTU相当于struct Student*
int main()
{
PSTU data;
data = (PSTU)malloc(sizeof(STU));
data->score = 100;
data->name = (char*)malloc(128);
memset(data->name,'\0',128);
data->name = "小红";
printf("名字是:%s\n分数是%d\n",data->name,data->score);
system("pause");
return 0;
}
在这里PSTU就相当于struct Student *,定义结构体指针变量的时候直接PSTU data ; 就可以了,当然要注意用malloc开辟空间,防止野指针,出现段错误。
在这里用typedef定义了结构体后,Student这个名字就可以去掉了。
如果在结构体成员里面定义了一个函数指针,函数指针实际参数为当前结构体时
typedef struct Student
{
int score;
char *name;
void (*p)(struct Student data);
}STU;
显然这个是可以运行的,因为struct Student在 { } 外面就已经有了,而void (*p)(struct Student data)在结构体里面。
而下面这种情况就不能运行
typedef struct Student
{
int score;
char *name;
void (*p)(STU data);
}STU;
因为STU首次出现是在 { } 外面,而void (*p)(STU data) 在结构体里面,typedef的执行步骤是先有结构体后,在typedef一下STU,所以会不认识STU,如果硬要这样写该怎么写呢?
typedef struct Student STU,*PSTU;
struct Student
{
int score;
char *name;
void (*p)(STU d);
};
这样写也可以,先出现STU,在结构体里面就可以使用了。