用C语言编写一个函数指针程序,有两个自定义的函数,分别叫fun_h和fun_k,当用户输入1时,调用fun_h函数,否则调用fun_k函数,要求使用函数指针进行调用。 编写一个函数指针程序,有两个自定义的函数,分别叫fun_h和fun_k,当用户输入1时,调用fun_h函数,否则调用fun_k函数,要求使用函数指针进行调用。
时间: 2024-04-07 18:33:06 浏览: 20
以下是一个使用函数指针的程序,根据用户的输入调用不同的自定义函数:
```c
#include <stdio.h>
void fun_h()
{
printf("调用了fun_h函数\n");
}
void fun_k()
{
printf("调用了fun_k函数\n");
}
int main()
{
int choice;
void (*func_ptr)(); // 声明函数指针
printf("请输入 1 或 2:");
scanf("%d", &choice);
if (choice == 1)
func_ptr = fun_h; // 函数指针指向fun_h函数
else
func_ptr = fun_k; // 函数指针指向fun_k函数
func_ptr(); // 调用函数指针所指向的函数
return 0;
}
```
在这个程序中,我们首先声明了一个函数指针`func_ptr`,该指针可以指向不返回值且不接受任何参数的函数。然后,我们根据用户输入选择将函数指针指向`fun_h`或`fun_k`函数。最后,我们通过`func_ptr()`调用函数指针所指向的函数。
希望这个程序能够满足您的需求!如果您有任何其他问题,请随时提问。
相关问题
C语言编写一个函数fun(char* s),该函数的功能是把字符串中的内容逆置
你可以使用指针来实现字符串的内容逆置。以下是一个用C语言编写的函数`fun`的示例代码:
```c
#include <stdio.h>
#include <string.h>
void fun(char* s) {
int length = strlen(s);
char* start = s;
char* end = s + length - 1;
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
char str[] = "Hello, World!";
printf("原始字符串:%s\n", str);
fun(str);
printf("逆置后的字符串:%s\n", str);
return 0;
}
```
在这个示例中,函数`fun`接受一个字符指针`s`作为参数,代表要逆置的字符串。首先,使用`strlen`函数获取字符串的长度。然后,使用两个指针`start`和`end`分别指向字符串的首尾字符。通过交换`start`和`end`指向的字符,并且让`start`指针向后移动,`end`指针向前移动,直到`start`指针不再小于`end`指针为止,完成字符串内容的逆置。
在`main`函数中,我们定义了一个字符串`str`,并将其作为参数传递给函数`fun`进行逆置。最后,打印逆置后的字符串结果。
运行上述代码,输出结果如下:
```
原始字符串:Hello, World!
逆置后的字符串:!dlroW ,olleH
```
希望能帮助到你!如有任何疑问,请随时提问。
用c语言编写一个函数fun,对字符进行判断,将大写字母转换成小写字母
好的,我会为您解答。请参考以下代码:
```c
#include <stdio.h>
void fun(char *str) {
int i = 0;
while (str[i]) {
if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] + 32;
}
i++;
}
}
int main() {
char str[] = "HELLO WORLD";
fun(str);
printf("%s\n", str);
return 0;
}
```
以上代码中,函数 `fun` 接收一个 `char` 类型的指针参数 `str`,循环遍历这个字符串中的所有字符。如果遇到大写字母,则将 ASCII 码值增加 32 后,将其转换为相应的小写字母。最后,在主函数中打印转换后的字符串。
希望这个代码对您有帮助。如果您还有其他问题,请随时问我。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)