用函数指针数组的方式,写一个参数为字符串,并执行动作的程序
时间: 2023-05-24 18:03:43 浏览: 59
A:
假设我们有一个字符串数组actions,每个元素都是一个指向函数的指针,函数接收一个字符串参数并执行相应的动作。然后我们定义一个函数execute_action,该函数接收一个字符串参数和一个整数参数,根据整数参数选择要执行的动作,并调用相应的函数执行。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
void action1(char *str) {
printf("Action 1: %s\n", str);
}
void action2(char *str) {
printf("Action 2: %s\n", str);
}
void action3(char *str) {
printf("Action 3: %s\n", str);
}
void execute_action(char *str, int index) {
void (*actions[])(char *) = {action1, action2, action3};
actions[index](str);
}
int main() {
char str[100];
int index;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline character
printf("Enter an index (0-2) to select an action: ");
scanf("%d", &index);
execute_action(str, index);
return 0;
}
```
这个程序中定义了三个动作函数,分别是action1、action2和action3。它们的参数都是一个字符串,但它们可以执行不同的动作。然后我们定义了一个函数指针数组actions,每个元素都指向一个动作函数。在execute_action函数中,我们根据传入的整数参数选择要执行的动作,并直接调用相应的函数执行。最后在main函数中,我们读入一个字符串和一个整数,然后调用execute_action函数执行相应的动作。