卡在数组和字符串中与strcmp c 为什么它有效?? 编译器卡在if(strcmp(c,ch[i]) == 0){
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char ch[]="asdfghjkl";
char c;
int n=sizeof(ch)/sizeof(char);
scanf("%c",&c);
for(int i=0;i<n;i++){
if(strcmp(c,ch[i]) == 0){
printf("%c is in %dn",c,i+1);
break;
}else if(i==n-1){
printf("%c not fondn",c);
}
}
return 0;
}
我相信你的编译器应该抱怨你错误地使用了strcmp
:你把两个字符传递给两个const char*
,这绝对是一个UB。如果您的编译器通过抛出错误来阻止您这样做,那就太好了。
strcmp
的原型是(string.h
(
int strcmp(const char * s1, const char * s2);
由于您有两个字符并且char
是基本类型,因此您可以直接比较它们:
if ( c == ch[i] )
strcmp 的声明: int strcmp(const char *s1, const char *s2(;
strcmp 需要字符串,但您正在尝试传递字符。
用
if (c == ch[i])