目录
2.在单片机开发当中使用typedef比较常见,寄存器8位,16位,32位
3.2重命名的另一种,把结构体本身给的名字Student的去掉。
1.typedef关键字干嘛的
- typedef为C语言的关键字
- 作用是为一种数据类型定义一个新名字。
- 这里的数据类型包括内部数据类型(int,char等)和自定义数据类型(struct等)
- 和struct来匹配是为了代码编写简洁
- 和普通类型匹配,通过名字来获取一些信息
2.在单片机开发当中使用typedef比较常见,寄存器8位,16位,32位
- 在寄存器中比如一个char型,其实是可以在寄存器8位,16位,32位中重合的,都可以有其表示的方式。
- 比如数据在寄存器8位已经足够,你配了一个32位的寄存器给他,就会造成浪费。为了给人有好的阅读,所以用了typedef重命名。
typedef unsigned char u_int8; // 无符号的字符型 此时就是将unsigned char这一串命名为u_int8,对应寄存器8位。
typedef unsigned short int u_int16; //无符号的短整型 此时就是将unsigned short int 这一串命名为u_int16
typedef unsigned int u_int32;
3. 和结构体结合命名:
3.1普通重命名。
typedef struct Student
{
int score;
char *name;
void (*p)(struct Student stu); //void (*p)(STU stu); 不可以换成这样,因为STU是在结构体的定义大括号之后,先有大括号里的才开始外面。
}STU;
此时:struct Student 就相当于 STU
3.2重命名的另一种,把结构体本身给的名字Student的去掉。
typedef struct
{
int score;
char *name;
}STU;
3.3普通重命名后附带命名一个指针(最常见)。
typedef struct Student
{
int score;
char *name;
void (*p)(struct Student stu); //void (*p)(STU stu); 不可以换成这样。因为STU是在结构体的定义大括号之后,先有大括号里的才开始外面。
}STU *PSTU;
STU 就相当于 struct Student
*PSTU 就相当于 struct Student* 是一个指针
3.3结构体里的函数指针,不能使用结构体括号外的名字
比如上面的代码中的:void (*p)(struct Student stu);
不可以写成: void (*p)(STU stu);
因为STU是在结构体的定义大括号之后,先有大括号里的才开始外面。
4. typedef关键字和结构体的使用,代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char u_int8;
typedef unsigned short int u_int16;
typedef unsigned int u_int32;
typedef struct Student
{
int score;
char *name;
void (*p)(struct Student stu); //void (*p)(STU stu); 不可以。因为STU是在结构体的定义大括号之后
}STU,*PSTU;
int main()
{
//单片机开发中常见
u_int8 data = 10;
u_int16 data2 = 20;
u_int32 data3 = 40;
printf("%d,%d,%d\n",data,data2,data3);
//未加指针变量,只有STU时 struct Student stu1;
STU stu1;
stu1.score = 100;
printf("Score=%d\n",stu1.score);
//typedef之后的结构体用法。在结构体那里加了指针变量*PSTU后 struct Student* pstu
PSTU pstu;
pstu = (PSTU)malloc(sizeof(STU));
pstu->score = 99;
printf("Score2=%d\n",pstu->score);
//旧结构体用法
struct Student* pstu3;
pstu3 = (struct Student*)malloc(sizeof(struct Student));
pstu3->score = 99;
printf("Score3=%d\n",pstu3->score);
system("pause");
return 0;
}