typedef use

typedef is doing

typedef is used to define a new type of

New here has two meanings:

1, the old type to the new name

For example: typedef INT int; saying the program should be used in place int INT consistent use of some do not take your pants fart is in fact not ??? This practice is common in transplant int length on some systems... For example, some systems are not the same on a 16-bit int length, this time using int_16 represent only need to write typedef iNT int_16;.. then the program will be replaced by int_16 iNT type this type in line with the new system some time here. You may be used #define. Alternatively to
give an example:

int *p;
上面这句话大家都知道是定义了一个int*类型的指针变量p 
现在问你一个问题,p是个变量,那么p的类型是什么?
你一看,这不是废话么.p的类型当然是int *类型的了.说成人话就是,p的类型是`整型的指针类型`.
(这句话里有个整型,这个型是和整在一起的,整型是一个词,表示这个位置应该是个数字,所以可以这么说,p的类型是数字的指针类型,p的内容是个地址,这个地址上只能存数字,还是个整数数字).
现在明白了p的类型了,我们再来看看下面这句话.

typedef int *p;
这句话是使用了typedef来将int *类型使用了一个标识符p来进行代替.这个式子里就一个p不是关键字.
经过这句话后,就是给int *起了一个别名叫p
所以以后声明新的整型指针变量的时候可以直接使用p来进行声明了.
比如: p a; 这句话就和 int * a;是一样的.
我们怎么理解p是int *的类型?
首先看int *p;
这个p是int *类型的,然后再前面加上了typedef后,p就表示这个类型了.这个弯要转过来哦.

2, the definition of a new type

This is a place we are very puzzled. What is a new type? Not our common base type. For example, 函数指针类型variables, 指针数组类型variables.

直接上例子
int add(int a, int b);首先定义了一个求和函数.

int (*func)(int, int);这句话是声明了一个函数指针(不明白的去看一下我的其他博文).
这句话写出来之后,就是和 int x;没有区别,就是声明了一个变量.
int (*func)(int, int);声明了一个指针变量叫func,由于它是一个函数指针,所以它应该有所指向,并且应该指向一个函数.它指向了一个返回值是int,形参是(int,int)的这样的函数(也就是指向了add那样的函数).
既然是这样的函数(这样的函数是个什么样的函数?返回值是int,形参是(int,int)的函数),我们是不是可以给这样的函数起个名字啊?
当然可以啊.
那我们是不是也可以把这样的函数叫做这个类型的函数啊?
当然可以啊.

好,那我们来起名字.
typedef int (*this_type)(int, int);
这样就给这样的函数起了个名字叫`this_type`.
以后我们就可以使用this_type来声明一个函数指针了.
this_type mins_func;//声明了一个叫做mins_func的函数指针,mins_func指向 `返回值是int,形参是(int,int)的函数`


举个完整例子(这个例子,我自己实际运行过的,输出ok)
#include <stdio.h>
//我们定义一个求差的函数
int mins(int a, int b);//这句是声明
//下面这个是具体实现
int mins(int a, int b){
    return a-b;
}

typedef int (*this_type)(int, int);

//现在我们写一个main函数
int main(){
    int cha = 0;
    this_type mins_func; //声明函数指针
    mins_func = mins;    //给函数指针赋值
    cha = mins_func(3, 4);    //调用函数指针指向的函数
    printf("3 - 4 = %d\n", cha);
    return 0;
}

3, summary

How to use typedef to define a new type? ? ?

First, write variables (such as an identifier p, such as func), how are generally defined, such as function pointers, an array of pointers need to be defined
and then preceded typedef
last you write that p, that is the new type func name.
is that typedef function, which is to put out a statement before the variable name converted into a new type name.

Guess you like

Origin www.cnblogs.com/dhu121/p/12160281.html