那怎么输出函数指针pf呢
时间: 2024-06-04 16:04:07 浏览: 13
要输出一个函数指针,您可以使用以下方式:
1. 直接输出指针地址,例如:
```
printf("%p", pf);
```
这将输出函数指针pf的地址。
2. 将函数指针赋值给另一个指针变量,然后输出该指针变量的地址,例如:
```
int (*pf)(int);
int (*p)(int);
p = pf;
printf("%p", p);
```
这将输出函数指针pf的地址。
3. 通过函数指针间接调用函数并输出其返回值,例如:
```
int (*pf)(int);
int a = 5;
int result = pf(a);
printf("%d", result);
```
这将通过函数指针pf调用函数并输出其返回值。
相关问题
C语言 打印函数指针的函数名%Fp %pf
在C语言中,我们可以通过使用函数指针来动态地调用不同的函数。在使用函数指针时,有时候需要打印函数指针的函数名,这时可以使用格式化输出函数printf()中的%Fp或%pf占位符来实现。
%Fp用于以十六进制输出函数指针,并在输出前加上函数名和文件名;%pf则只输出函数指针本身。需要注意的是,使用%Fp或%pf占位符需要包含头文件<stdio.h>。
示例代码:
```c
#include <stdio.h>
void func()
{
printf("This is func()\n");
}
int main()
{
void (*p)() = func;
printf("%Fp\n", p);
printf("%pf\n", p);
return 0;
}
```
输出结果:
```
0x4004b6 <func> at test.c
0x4004b6
```
(3)定义并使用函数指针pf,使其指向函数int strcmp(const char*,const char*);实现通过指针pf调用函数strcmp()
可以照以下步骤定义并使用函数指针pf,使其指向函数int strcmp(const char*,const char*):
1. 定义函数指针类型,指向返回值为 int,参数为两个 const char* 的函数:
```c++
typedef int(*PF)(const char*, const char*);
```
2. 声明函数指针变量 pf,并将其指向 strcmp 函数:
```c++
PF pf = strcmp;
```
3. 通过函数指针 pf 调用 strcmp 函数:
```c++
const char* str1 = "hello";
const char* str2 = "world";
int result = pf(str1, str2);
```
完整代码如下:
```c++
#include <iostream>
#include <cstring>
typedef int(*PF)(const char*, const char*);
int main()
{
const char* str1 = "hello";
const char* str2 = "world";
PF pf = strcmp;
int result = pf(str1, str2);
std::cout << "result: " << result << std::endl;
return 0;
}
```
运行结果为:
```
result: -15
```
说明通过函数指针 pf 成功调用了 strcmp 函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)