(3)定义并使用函数指针pf,使其指向函数int strcmp(const char*,const char*);实现通过指针pf调用函数strcmp()
时间: 2024-02-28 21:55:48 浏览: 19
可以照以下步骤定义并使用函数指针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 函数。