为什么形参(void (*p)(char *))是常量?
题目描述
用一个回调函数,打印出 str
的内容
题目来源及自己的思路
来源:鹏哥c语言
相关代码
#include<stdio.h>
void print(char *str)
{
printf("hehe%s",str);
}
void test(void(*p)(char*))
{
printf("test\n");
p("abcdefg");
}
int main()
{
test(print);
//调用test函数,参数是print函数
return 0;
}
你期待的结果是什么?实际看到的错误信息又是什么?
按道理来说,应该是通过 test
函数调用 print
函数,打印出来 heheabcdefg
,但实际会报错
const char * 类型的实参与 char * 类型的形参不兼容;
回复
1个回答

test
2024-07-13
你理解错了,这个错误说的是 "abcdefg" 是 const char*
,而你的 p 函数定义的是接收 char*
,所以才报错,你需要改成:
#include<stdio.h>
void print(const char *str)
{
printf("hehe%s",str);
}
void test(void(*p)(const char*))
{
printf("test\n");
p("abcdefg");
}
int main()
{
test(print);
//调用test函数,参数是print函数
return 0;
}
就可以了。
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容