char[5]="hello"和char *p="hello"区别

第一个是一个字符数组(或者后边加一个‘\0’叫字符串数组),如果那样写不明确,可以明确的这样写:char c[5]={'h','e','l','l','o'};这就一个数组。如果是在局部函数中是放在栈中的,不能返回c在主函数中打印的,因为局部函数结束,c[5]的生命周期也就结束了。
char *p="hello",是字符串常量,存于rodata段,所以如果在局部函数中返回p也是可以的,在局部函数结束的时刻它把hello的rodata段中的地址返回,主函数中可以用的。
这个涉及到了程序在内存中的分部。
#include <stdio.h>
#include <malloc.h>
char *func1(void)
{
char s[5] = "hello";
return s;
}
char *func2(void)
{
char *p = "world";
return p;
}
int main(void)
{
printf("func1() = %s\n", func1());
printf("func2() = %s\n", func2());
return 0;
}