深入分析C++中char * 和char []的区别
在程序员面试宝典上看到这个两句话:
1、char c[]="hello world"是分配一个局部数组;
2、char *c="hello world"是分配一个全局数组;
最开始还以为是书上说错了,因为自己的理解是这两种方式是等效的。下来查了一下才知道这两种方式的区别。
char* str="hello world ";这个指针指向常量字符串,存储在静态存储区,是只读的,不能被修改。而char str[]="hello world"是一个局部变量数组,存储在栈上的内存空间,可以被修改。
拿程序员面试宝典上的例子来说:
- <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将指向无效的地址空间。因此是乱码。