参考自: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 *”