C/C++把常量字符串放到单独的一个内存区域。当几个指针赋值给相同的常量字符串时,它们实际上会指向相同的内存地址。但用常量内存初始化数组,情况却有所不同。
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char str1[] = "helloworld";
char str2[] = "helloworld";
char* str3 = "helloworld";
char* str4 = "helloworld";
if (str1 == str2)
printf("str1 and str2 are the same\n");
else
printf("str1 and str2 are not the same\n");
if (str3 == str4)
printf("str3 and str4 are the same\n");
else
printf("str1 and str2 are not the same\n");
return 0;
}
则输出
str1 and str2 are not the same
str3 and str4 are the same