C++ char[] 和char*在VS2007中的存储位置

参考自:https://blog.csdn.net/u013654125/article/details/79758286 

测试代码如下:

char str1[] = "abc";
char str2[] = "abc";
const char str3[] = "abc";
const char str4[] = "abc";
const char *str5 = "abc";
const char *str6 = "abc";
//下面两行代码在VS2007中无法编译通过
//char *str7 = "abc"; 
//char *str8 = "abc";
cout << (str1 == str2) << endl; 
cout << (str3 == str4) << endl;
cout << (str5 == str6) << endl;
//VS2007中不支持.
//cout << (str7 == str8) << endl;

我们来看看上面的代码编译后的汇编语言是什么情况:

    39:     char str1[] = "abc";
012162D2  mov         eax,dword ptr [string "abc" (01219BC4h)]  
012162D7  mov         dword ptr [str1],eax  
    40:     char str2[] = "abc";
012162DA  mov         eax,dword ptr [string "abc" (01219BC4h)]  
012162DF  mov         dword ptr [str2],eax  
    41:     const char str3[] = "abc";
012162E2  mov         eax,dword ptr [string "abc" (01219BC4h)]  
012162E7  mov         dword ptr [str3],eax  
    42:     const char str4[] = "abc";
012162EA  mov         eax,dword ptr [string "abc" (01219BC4h)]  
012162EF  mov         dword ptr [str4],eax  
    43:     const char *str5 = "abc";
012162F2  mov         dword ptr [str5],offset string "abc" (01219BC4h)  
    44:     const char *str6 = "abc";
012162F9  mov         dword ptr [str6],offset string "abc" (01219BC4h)  
    45: 	//被注释的部分, VS2007不支持.
    46:     //char *str7 = "abc";
    47:     //char *str8 = "abc";

从上述汇编代码中可以看出, 所有的"abc"都存放在常量区, 地址为(01219BC4h)

str1,str2,str3,str4 从汇编语言中明显看出是不同的地址. 因此 它们4个变量不会相等. 

而后面的str5和str6是两个指针, 指向的同一个地址(01219BC4h),因此是相等的. 

至于str7和str8在VS2007中编译无法通过, 错误如下:

C2440    “初始化”: 无法从“const char [4]”转换为“char *”  


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值