为什么在我的C代码中,两个不同的调用会返回相同的结果?

时间:2019-03-25 01:18:54

标签: c

我已经使用GCC(4.9.2)在Debian平台上对其进行了编译。

#include <string.h>
#include <stdio.h>

static const char *msg[] = {"Sunday", "Monday", "Thuesday"};
static char buf[20];

char *getday(int idx) {
    strcpy(buf, msg[idx]);
    return buf;
}

int main(void) {
    printf("%s %s\n", getday(0), getday(1));
    return 0;
}

看起来不错,但始终打印相同的字符串(星期日)。但是为什么?

2 个答案:

答案 0 :(得分:1)

printf本身之前会调用printf的参数中的

函数。由于两个调用都将地址返回到相同的缓冲区,因此上一个调用将创建其内容。 (没有定义的顺序来调用参数中的函数)。

因此,您使用3个arg调用printf,其中后2个具有指向相同缓冲区的相同内容的相同指针。

答案 1 :(得分:1)

Not being there I enjoyed a lot seeing the life style of white bear. Thanks to the provider for such documentary. WOOOW... amazing... I've been photographing polar bears for years, but to see this footage from a drones perspective was epic! Well done and congratz on the Nominee! Well deserved. You are da man Florian! Absolutely outstanding! This is incredible jaw dropping This is wow amazing, love it. So cool! Did the bears react to the drone at all? Congratulations! It's awesome! I am watching in tears.... Awesome! perfect video awesome It is very, very beautiful !!! Sincere congratulations Made my day, exquisite, thank you Wow Super! Marvelous! Man this is incredible! Material is good, but edi is bad. This history about beer's family... Muy bueno! 返回getday的地址。因此buf两次获得相同的参数(printf的地址)。 buf评估其参数时,buf包含字符串“ Sunday” ,因为首先执行printf(在您的情况下,编译器首先选择最右边的参数),用字符串“ Monday” 填充getday(1),然后执行buf,用字符串“ Sunday” 填充getday(0) ,然后buf使用给定地址(“星期日”)上的数据。

要解决此问题,您必须将printf的返回值复制到单独的本地缓冲区中并将其传递到getday(),或者每次必须返回不同的地址,例如通过返回数组printf而不是msg中的地址,例如所以:

buf