#include <stdio.h>
char *test()
{
char *p = "hello world";
return p;
}
int main()
{
char *p = test();
printf("%s\n", p);
return 0;
}
輸出:hello world
#include <stdio.h>
char *test()
{
char p[] = "hello world";
return p;
}
int main()
{
char *p = test();
printf("%s\n", p);
return 0;
}
輸出錯誤!
區別:如果是指針p,則p指向存放字符串常量的地址,返回p則是返回字符串常量地址值,調用函數結束字符串常量不會消失(是常量)。所以返回常量的地址不會出錯。
如果是數組p,則函數會將字符串常量的字符逐個複製到p數組裏面,返回p則是返回數組p,但是調用函數結束後p被銷燬,裏面的元素不存在了。