#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
static char s1[]="Good";
static char s2[20];
static char s3[20]="Day";
int i = strcmp(strcat(s3,strcpy(s2,s1)),strcat(s3,"good"));
printf("%d\n",i);
return 0;
}
这里的输出是0,这意味着作为参数传递给
strcmp
的两个字符串是相等的但是对于strcmp
,第一个参数是"DaygoodGood"
,第二个参数是"Daygood"
。。。为什么会这样?
最佳答案
不管你怎么看,你都在比较s3
和s3
你这样做总是一样的把它分解-改变:
i=strcmp(strcat(s3,strcpy(s2,s1)),strcat(s3,"good"));
进入:
char *s4 = strcpy(s2,s1); // s4 == s2 -> "Good"
char *s5 = strcat(s3,s4); // s5 == s3 -> "DayGood"
char *s6 = strcat(s3,"good"); // s6 == s3 -> "DayGoodgood"
i = strcmp(s5, s6); // same as strcmp(s3, s3)
不管是真的这样,还是:
char *s4 = strcpy(s2,s1); // s4 == s4 -> "Good"
char *s6 = strcat(s3,"good"); // s6 == s3 -> "Daygood"
char *s5 = strcat(s3,s4); // s5 == s3 -> "DaygoodGood"
i = strcmp(s5, s6); // same as strcmp(s3, s3)
相反,标准未明确规定不管怎样,您是在比较相同的字符串,不管连接发生的顺序如何你要么比较
"DayGoodgood"
到"DayGoodgood"
或者"DaygoodGood"
到"DaygoodGood"
,但是你应该期望无论哪种方式都会导致0
。