char* strA(){
char str[] = "hello world";
return str;
}
const char* strB(){
char* str = "hello world";
return str;
char str[] = "hello world";
return str;
}
const char* strB(){
char* str = "hello world";
return str;
}
这两个函数,第一个会失败,第二个会成功。因为第一个str里存的是strA栈帧里的“hello world”的首地址,函数调用完成之后,空间收回。第二个str分配一个全局数组,对应内存中全局区域,字符串常量保存在只读的数据段。
char * c = "hello world";
char a[] = "hello world";
*c = 't'; //这一句会出错
*a = 't'; //OK
c指向只读数据段,内容不能被修改。而a占用局部区数据,可以修改。