关于strncmp的疑问
程序如下:#include <stdio.h>
#include <string.h>
int main(void){
/*定义三个内容相似的字符串*/
char str1[]="long time";
char str2[]="long time";
char str3[]="lonG time";
int length=strlen(str1);
/*分别输出三个字符串的内容*/
printf("str1=\"%s\"\n",str1);
printf("str2=\"%s\"\n",str2);
printf("str3=\"%s\"\n",str3);
/*演示strncmp函数的使用*/
printf("strncmp(str1,str2,%d)=%d\n",
length,strncmp(str1,str2,length));
printf("strncmp(str3,str1,%d)=%d\n",
length,strncmp(str3,str1,length));
printf("strncmp(str1,str3,%d)=%d\n",
length,strncmp(str1,str3,length));
printf("strncmp(str1,str3,3)=%d\n",
length,strncmp(str1,str3,3));
printf("g-G=%d\n",'g'-'G');
return 0;
}
gcc下执行结果:
str1="long time"
str2="long time"
str3="lonG time"
strncmp(str1,str2,9)=0
strncmp(str3,str1,9)=-32
strncmp(str1,str3,9)=32
strncmp(str1,str3,3)=9
g-G=32
红色部分比较的是str1和str3的前3个字符的大小,因为str1和str3前3位都一样,为什么输出结果不是0,而是9?