函数指针
#include<stdio.h>#include<stdlib.h>
#include<string.h>
void check(char *x,char *y,int (*comp)(char *,char *))
/*第三个参数为函数指针变量*/
{
if(!(*comp)(x,y))
printf("相等\n");
else
printf("不相等\n");
}
int compvalues(char *x,char *y)
{
if(atoi(x)==atoi(y))
/*atoi()将字符串类型转换成整型,需要包含头文件stdlib.h*/
return 0;
else
return 1;
}
void main()
{
char a,b;
strcpy(a,"0123");
strcpy(b,"123");
printf("比较数值是否相等:\n%s与%s",a,b);
check(a,b,compvalues);
printf("比较字符串中是否相等:\n%s与%s",a,b);
check(a,b,strcmp);
}
//编写一个函数,使用函数指针变量作为参数,使其即可比较字符串是否相等,也可比较数值是否相等。
//大佬们啊,看不懂啊!!! 你是什么看不懂啊,不清楚你要问什么 你这个可以运行吗/?
int mystrcmp(char *x,char*y)
{
int i=0;
for(i=0;i<80;i++)
{
if(*x++ != *y++)
{
return 1;
}
}
return 0;
}
自己写一个,compvalues和strcmp,IntelliSense: "int (__cdecl *)(const char *_Str1, const char *_Str2)" 类型的实参与 "int (*)(char *, char *)" 类型的形参不兼容
本帖最后由 小甲鱼的铁粉 于 2020-12-21 20:28 编辑
是因为你的compvalues的形参类型和strcmp函数形参类型出现了矛盾
先看strcmp函数int __cdecl strcmp(const char *_Str1,const char *_Str2);,他在string.h中是这样定义的,形参都时const char但是你的compvalues的形参都是char,就矛盾了
所以可以修改一下compvalues的形参,正确的如下
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void check(char *x,char *y,int (*comp)(const char *,const char *))
/*第三个参数为函数指针变量*/
{
if(!(*comp)(x,y))
printf("相等\n");
else
printf("不相等\n");
}
int compvalues(const char *x,const char *y)
{
if(atoi(x)==atoi(y))
/*atoi()将字符串类型转换成整型,需要包含头文件stdlib.h*/
return 0;
else
return 1;
}
int main()
{
char a,b;
strcpy(a,"0123");
strcpy(b,"123");
printf("比较数值是否相等:\n%s与%s",a,b);
check(a,b,compvalues);
printf("比较字符串中是否相等:\n%s与%s",a,b);
check(a,b,strcmp);
} 小甲鱼的铁粉 发表于 2020-12-21 20:06
你这个可以运行吗/?
我这个就是有错误。strcmp会报错 小甲鱼的铁粉 发表于 2020-12-21 20:27
是因为你的compvalues的形参类型和strcmp函数形参类型出现了矛盾
先看strcmp函数,他在string.h中是这样定 ...
大佬,你上面回复的我都看懂了。但是我是想问一下这个程序我怎么理解? 小甲鱼的铁粉 发表于 2020-12-21 20:27
是因为你的compvalues的形参类型和strcmp函数形参类型出现了矛盾
先看strcmp函数,他在string.h中是这样定 ...
我就是不知道,他这个程序是怎么打印出相等和不相等的 严凯 发表于 2020-12-22 18:33
我就是不知道,他这个程序是怎么打印出相等和不相等的
比如说他check(a,b,compvalues);
ckeck里面的第三个变量传入的是函数名,其实就是compvalues函数的入口地址
然后在check函数第三个形参int (*comp)就指向这个入口地址,然后就可以使用(*comp)(x,y),
(*comp)(x,y)就和compvalues(x,y)一样的,他们都是一个代码块上的函数
页:
[1]