C - 11:14:警告:传递'strcmp'的参数 1 会从整数生成指针而不进行强制转换



如果我去掉函数&;int check(charinp)&;把它的代码放在main中;程序运行良好。但是当我尝试创建一个单独的函数来检查输入时,我得到了错误。

#include <stdio.h>
#include <string.h>
/*trying to create a function that handles the "strcmp" functions*/
int check(char inp)
{
/*int c in this function holds the return value*/
int c;
char option1[20] = "cute puppy";
char option2[20] = "good evening frank";
char option3[20] = "are those new shoes";

/*checks input against "option" variables for a match*/
if (strcmp(inp, option1) == 0)
{
c = 1;
}
else if (strcmp(inp, option2) == 0)
{
c = 2;
}
else if (strcmp(inp, option3) == 0)
{
c = 3;
}
return c;
}
int main(void)
{
/*variable that stores input*/
char inp[20];

printf("You begin by walking down the sidewalk just outside your house.n"
"Its 11pm, nobody is out except your neighbor who is walking his dog.n"
"What do you say as you walk past?nn"
"cute puppy - good evening frank - are those new shoesn");
/*gets input from user and places it in "inp"*/
gets(inp);
/*if match is found int value is returned and assigned to "c" in "main"*/
int c = check(inp);
if (c == 1)
{
printf("works1n");
return 0;
}
else if (c == 2)
{
printf("works2n");
return 0;
}
else if (c == 3)
{
printf("works3n");
return 0;
}
return 0;
}

play.c:在函数'check'中:play.c:11:14:警告:传入'strcmp'的参数1使指针从整数转换而没有强制转换[-Wint-conversion]If (strcmp(inp, option1) == 0)

函数形参声明不正确。而不是类型char

int check(char inp);

其类型应为const char *

int check( const char * inp);

当传入的字符串不等于函数中定义的任何字符串时,函数调用未定义行为。

函数可以如下方式定义

int check( const char *inp )
{
size_t i = 0;

const char * options[] = 
{ 
"cute puppy", "good evening frank", "are those new shoes"
};

const size_t n = sizeof( options ) / sizeof( *options );

while ( i != n && strcmp( options[i], inp ) != 0 ) ++ i;

return i == n ? -1 : i;
}

注意gets函数是不安全的,不被C标准支持。而是使用函数fgets。例如

fgets( inp, sizeof( inp ), stdin );
inp[ strcspn( inp, "n" ) ] = '';

错误告诉您,第11行传递给strcmp的第一个参数是整数而不是指针。这是因为char在C中是整数类型,并且在第5行check函数的定义中,您指定inpchar而不是char*(指向char的指针),因此它认为inp的类型是。

最新更新