【发布时间】:2019-12-09 07:07:16
【问题描述】:
在 C 中使用以下程序,字符串比较不起作用:
#include<stdio.h>
#include<string.h>
int main(){
char ch[]="ABC";
printf("%d \n", strlen(ch)); // output 3
printf("%d \n", strlen("ABC")); // output 3
if(strcmp("ABC",ch)){
printf("\n Matched");
}else{
printf("\n Not matched"); // this will be output
}
if("ABC" == ch){
printf("\n Matched");
}else{
printf("\n Not matched"); // this will be output
}
}//ends main
输出是:
3
3
Not matched
Not matched
为什么字符串不匹配?
【问题讨论】:
-
坦率地说,所有这些都应该通过任何体面的书籍、教程或课程来解释。
-
另外,
strlen函数返回一个size_t类型的值,其正确的printf格式说明符是%zu。参数类型和格式说明符不匹配导致undefined behavior。
标签: c string string-comparison