关于static指针的一个严重问题

来源:互联网 发布:深圳中航软件 编辑:程序博客网 时间:2024/04/20 15:04

 1 #include <stdio.h>
  2 #include <string.h>
  3
  4 static const char *msg[] ={"Sunday", "Monday", "Tuesday","Wednesday ", "Thur    sday", "Friday", "Saturday"};
  5 char *get_a_day(int index)
  6 {
  7     static char buf[20];//主义这里
  8     strcpy(buf, msg[index]);
  9     return buf;
 10 }
 11 int main(int argc, char *argv[])
 12 {
 13     printf("%s %s/n", get_a_day(0), get_a_day(1));
 14
 15     return 0;
 16 }

~                    很简单的一个程序,但里面蕴含很严重的错误,那就是static 记住了static只分配一次内存,这里又是返回一个指针

所以,结果输出的不是Sunday Monday 而是俩个Sunday,因为俩个指针指向的同一块内存区域,所以会打出同一个值来