#include <stdio.h>
#include <stdlib.h>
char * favorite_fruit1(void);
char * favorite_fruit2(void);
void favorite_fruit3(char **);
int main(void) {
char * fruit1 = favorite_fruit1();
printf("%s\n", fruit1);
char * fruit2 = favorite_fruit2();
printf("%s\n", fruit2);
char * fruit3 = NULL;
favorite_fruit3(&fruit3);
printf("%s\n", fruit3);
printf("------END of CODE------");
return EXIT_SUCCESS;
}
char * favorite_fruit1(void){
char deciduous[] = "apple";
return deciduous;
}
char * favorite_fruit2(void){
static char deciduous[] = "apple";
return deciduous;
}
void favorite_fruit3(char ** fruit){
static char deciduous[] = "apple";
*fruit = deciduous;
}
favorite_fruit1很明显会出现问题,原因是因为char deciduous[]是局部变量,在函数调用返回后,就释放了。
favorite_fruit2因为使用了static,而static限定了变量被保存在数据段(data segment)中,它的声明周期同程序一样长。所以不会出错。
favorite_fruit3是另一种有效的写法,其原理同2。