# typedef指针

## 1.简单的函数指针的应用

形式1：返回类型(\*函数名)(参数表)

```c
char (*pFun)(int);   
char glFun(int a){ return;}   
void main()   
{   
    pFun = glFun;   
    (*pFun)(2);   
}
```

## 2.使用typedef更直观更方便

形式1：typedef 返回类型(\*新类型)(参数表)

```c
typedef char (*PTRFUN)(int);   
PTRFUN pFun;   
char glFun(int a){ return;}   
void main()   
{   
    pFun = glFun;   
    (*pFun)(2);   
}
```

## 3.例子说明

### **typedef定义函数指针**

```c
typedef int (*FP_CALC)(int,int);//定义一个函数指针类型  

int add(int a, int b)  
{  
    return a + b;  
}  

int sub(int a, int b)  
{  
    return a - b;  
}  

int mul(int a, int b)  
{  
    return a * b;  
}  

int div(int a, int b)  
{  
    return b ? a/b : -1;  
}  

//定义一个函数，参数为op，返回一个指针,该指针类型为拥有两个int参数、  
//返回类型为int的函数指针。它的作用是根据操作符返回相应函数的地址  
FP_CALC calc_func(char op)  
{  
    switch( op )  
    {  
    case '+':  
        return add;  
    case '-':  
        return sub;  
    case '*':  
        return mul;  
    case '/':  
        return div;  
    default:  
        return NULL;  
    }  
    return NULL;  
}
```

### **返回函数指针，直接定义**

```c
//s_calc_func为函数，它的参数是 op，     
//返回值为一个拥有两个int参数、返回类型为int的函数指针    
int (*s_calc_func(char op)) (int , int)  
{
    return calc_func(op);  
}
```

### 使用

```c
FP_CALC fp = calc_func(op);  
int (*s_fp)(int,int) = s_calc_func(op);//用于测试
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/c/typedef-zhi-zhen.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
