在我用C指针文献磨练我的C技能的过程中,我偶然发现了这段代码。在这个问题上,我应该证明输出是正确的。我熟悉strcat()和strcmp()的工作。我知道,当两个字符串被传递时,strcmp()返回0是相同的。
# include <stdio.h>
# include <string.h>
int main()
{
static char str1[]="Good";
static char str2[20];
static char str3[20] ="Day";
int l;
l = strcmp(strcat(str3, strcpy(str2, str1)), strcat(str3, "good"));
printf("%d\n", l);
return 0;
}这里提供的答案是0,这意味着两个计算的字符串必须是相同的。我试着用多个步骤来解决这个问题。
首先,尝试strcat(str3, strcpy(str2, str1))。'str2‘改为’Good‘,然后strcat()将str3改为’`DayGood‘。到目前为止,我的gcc编译器同意我的观点。
来到strcat(str3, "good")时,由于str3已经更改为DayGood,strcat将str3更改为DayGoodgood。
gcc又和我一起生气了。
int main()
{
static char str1[]="Good";
static char str2[20];
static char str3[20] ="Day";
int l;
printf("%s\n", strcat(str3, strcpy(str2, str1)));
printf("%s\n", strcat(str3, "good"));
//l = strcmp(strcat(str3, strcpy(str2, str1)), strcat(str3, "good"));
//printf("%d\n", l);
return 0;
}它产生
DayGood
DayGoodgood我又一次尝试了这种变体。
int main()
{
static char str1[]="Good";
static char str2[20];
static char str3[20] ="Day";
int l;
printf("%s\n", strcat(str3, "good"));
printf("%s\n", strcat(str3, strcpy(str2, str1)));
//l = strcmp(strcat(str3, strcpy(str2, str1)), strcat(str3, "good"));
//printf("%d\n", l);
return 0;
}它会产生。
Daygood
DaygoodGood在我的两个测试用例中,我得到两个不同的字符串进行比较。为什么strcmp()会产生0呢?
发布于 2013-07-27 21:47:08
有一种快速的方法可以在不跟踪所有调用的情况下得到答案:strcat的两个参数都是从strcpy的第一个arg str3返回的,而且由于strcpy返回其第一个arg,这意味着最后的调用是strcmp(str3, str3),当然,不管对它做了什么奇怪的操作,strcmp(str3, str3)都是0。
在回答更新的问题时,尝试一下,看看你是否得到了启发:
#include <stdio.h>
#include <string.h>
int main(void)
{
static char str1[]="Good";
static char str2[20];
static char str3[20] ="Day";
char *first, *second;
printf("str3 = %p => %s\n", (void *)str3, str3);
first = strcat(str3, strcpy(str2, str1));
printf("first strcat returned %p => %s\n", (void *)first, first);
printf("and now str3 = %p => %s\n", (void *)str3, str3);
second = strcat(str3, "good");
printf("second strcat returned %p => %s\n", (void *)second, second);
printf("and now first = %p => %s\n", (void *)first, first);
printf("and now str3 = %p => %s\n", (void *)str3, str3);
printf("Is it any surprise that strcmp(first,second) = %d?\n",
strcmp(first,second));
return 0;
}发布于 2013-07-27 21:47:33
无论编译器选择哪个顺序计算strcmp的参数,strcat总是返回其第一个参数。
因此,本质上是这样发生的:
... // execute strcat(str3, strcpy(str2, str1)) and strcat(str3, "good")
l = strcmp(str3, str3);发布于 2013-07-27 21:50:20
它返回0,因为这两个参数:
strcat(str3, strcpy(str2, str1))和
strcat(str3, "good")实际上返回相同的内容:分配给str3的内存地址。因此,strcmp返回0,因为它将变量str3与自身进行比较。
https://stackoverflow.com/questions/17902711
复制相似问题