C语言 函数指针 指针函数
时间: 2023-11-22 20:44:07 浏览: 51
函数指针和指针函数都是指针类型,但它们的含义不同。函数指针是指向函数的指针,而指针函数则是返回指针的函数。
函数指针的定义方式为:`返回值类型 (*指针变量名)(参数列表)`,例如:
```c
int add(int a, int b) {
return a + b;
}
int (*p)(int, int) = add; // 定义一个函数指针p,指向add函数
int result = (*p)(1, 2); // 调用add函数,计算1+2的结果
```
指针函数的定义方式为:`返回值类型 (*函数名)(参数列表)`,例如:
```c
int* createArray(int size) {
int* arr = (int*)malloc(size * sizeof(int));
return arr;
}
int* (*p)(int) = createArray; // 定义一个指针函数p,返回值为int*
int* arr = (*p)(10); // 调用createArray函数,创建一个大小为10的int数组
```
相关问题
c语言函数指针指针函数
C语言中有两个相关概念,函数指针和指针函数。
1. 函数指针(Function Pointers):函数指针是指向函数的指针变量。它可以用来存储和调用特定类型的函数。通过函数指针,可以在运行时动态地选择要执行的函数。函数指针的声明形式为:`返回类型 (*指针变量名)(参数列表)`。例如,以下是一个函数指针的示例:
```c
#include <stdio.h>
void display(int num) {
printf("Number: %d\n", num);
}
int main() {
void (*func_ptr)(int); // 声明一个函数指针变量
func_ptr = display; // 将函数的地址赋值给函数指针变量
func_ptr(10); // 通过函数指针调用函数
return 0;
}
```
2. 指针函数(Pointer to a Function):指针函数是一个返回指向函数的指针的函数。它返回的是函数的地址,而不是函数的返回值。指针函数的声明形式为:`返回类型 (*函数名)(参数列表)`。以下是一个指针函数的示例:
```c
#include <stdio.h>
int add(int num1, int num2) {
return num1 + num2;
}
int subtract(int num1, int num2) {
return num1 - num2;
}
int (*getOperation(char op))(int, int) {
if (op == '+') {
return add; // 返回add函数的地址
} else {
return subtract; // 返回subtract函数的地址
}
}
int main() {
int num1 = 10, num2 = 5;
char op = '+';
int (*operation)(int, int); // 声明一个指针函数变量
operation = getOperation(op); // 将指针函数的返回值(函数地址)赋值给指针函数变量
int result = operation(num1, num2); // 通过指针函数调用对应的函数
printf("Result: %d\n", result);
return 0;
}
```
以上就是函数指针和指针函数的基本概念和用法。通过它们,可以实现更灵活的函数调用和动态选择执行的函数。
c语言函数指针和指针函数
函数指针和指针函数都是指针类型的函数,但它们的定义和用法不同。
函数指针是指向函数的指针,用于存储函数的地址。它可以像普通指针一样进行赋值、传参和调用,例如:
```c
// 声明函数指针
int (*pFunc)(int, int);
// 定义函数
int add(int a, int b) {
return a + b;
}
// 指向函数的指针赋值
pFunc = add;
// 调用函数
int result = pFunc(1, 2); // result为3
```
指针函数是返回指针类型的函数,它的返回值是指针,例如:
```c
// 声明指针函数
int* getArray(int size) {
int* arr = (int*)malloc(sizeof(int) * size);
return arr;
}
// 调用指针函数
int* array = getArray(10);
```
在调用指针函数时,它会返回一个指向动态分配数组的指针。
总之,函数指针和指针函数虽然都是指针类型的函数,但它们的定义和用法是不同的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)