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

在程序员面试宝典上看到这个两句话:

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

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

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

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

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

[cpp] view plain copy
  1. <span style="font-size:18px;">char* strA()  
  2. {  
  3.     char* str = "hello world";  
  4.     return str;  
  5. }  
  6.   
  7. char* strB()  
  8. {  
  9.     char str[] = "hello world";  
  10.     return str;  
  11. }  
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     char* str = strA();  
  16.     cout << str << endl;  
  17.   
  18.     char* str2 = strB();  
  19.     cout << str2 << endl;  
  20.     return 0;  
  21. }</span>  
上述代码的输出结果为:

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

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

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

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

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

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

会清空栈的存储空间,因此,str2将指向无效的地址空间。因此是乱码。