您的位置:首页 > 编程语言 > C语言/C++

深入分析C++中char * 和char []的区别

2017-12-12 11:53 435 查看
在程序员面试宝典上看到这个两句话:

1、char c[]="hello world"是分配一个局部数组;

2、char *c="hello world"是分配一个全局数组;

最开始还以为是书上说错了,因为自己的理解是这两种方式是等效的。下来查了一下才知道这两种方式的区别。

char* str="hello world ";这个指针指向常量字符串,存储在静态存储区,是只读的,不能被修改。而char str[]="hello world"是一个局部变量数组,存储在栈上的内存空间,可以被修改。

拿程序员面试宝典上的例子来说:

[cpp] view
plain copy

<span style="font-size:18px;">char* strA()

{

char* str = "hello world";

return str;

}

char* strB()

{

char str[] = "hello world";

return str;

}

int _tmain(int argc, _TCHAR* argv[])

{

char* str = strA();

cout << str << endl;

char* str2 = strB();

cout << str2 << endl;

return 0;

}</span>

上述代码的输出结果为:



从图中可以看到,在主函数中strA函数,可以正常的输出"hello world"。

而调用strB时,输出则是乱码。

原因在于char* str = "hello world"中定义的str是存储在静态存储区中,具有全局属性,

所以函数结束时,能够正常返回指向存有hello world的内存单元,

而char str[] = "hello world"中的str是存储在栈上的局部变量数组,但函数运行结束时,

会清空栈的存储空间,因此,str2将指向无效的地址空间。因此是乱码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++