深入分析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>  
上述代码的输出结果为:



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

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

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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值