linux c 一站式学习 函数接口 返回值是指针的情况

来源:互联网 发布:插画制作软件 编辑:程序博客网 时间:2024/05/20 09:46

关于printf的小例子

#include<stdio.h>#include<string.h> #include<stdlib.h> char *get_a_day(int idx); static const char *msg[]={"sunday","monday","tuesday"}; char *get_a_day(int idx) {      static char buf[20];      for(int i=0;i<20;i++)             buf[i]=0;      strcpy(buf,msg[idx]);      return buf; } int main() {      printf("%s %s\n",get_a_day(0),get_a_day(1));      system("PAUSE");      return 0; } 

这段代码的输出为什么是sunday sunday啊 怎么不是sunday monday呢。。??求解 

分析:

printf执行时首先计算get_a_day(1),get_a_day函数返回的是buf的地址,这时buf指向的地址内容为 monday \0 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _(共20字节),然后由于buf是静态的,第二次调用get_a_day返回的仍然是buf的地址,经过第二次strcpy后buf地址变为 sunday \0 _ _ _ _ _ _ _ _ _ _ _ _ _(共20字节),然后调用printf时,get_a_day(0),get_a_day(1)分别入栈buf地址,于是打印出你看到的结果。
注意:先有get_a_day(1),再有get_a_day(0),最后才会调用printf。从右到左执行,buf里面存的是最左边执行完的结果,所有的函数参数返回的都是buf的地址,关键是那个static的问题。
貌似要正确输出 sunday和monday只能依靠printf的执行顺序了。 
比如这样: 
printf("%s\n",get_a_day(0)); 
printf("%s\n",get_a_day(1)); 

只要放在一个printf中,只能输出形参最左边的那个值。

http://blog.csdn.net/keyeagle/article/details/6708077/