1、代码
#include <stdio.h>
int main()
{
char str1[] = "hello word!!";
char str2[] = "hello word!!";
const char *str3 = "hello word!!";
const char *str4 = "hello word!!";
if(str1 == str2){
printf("str1 and str2 are same\n");
}
else{
printf("str1[0]=%c\n",str1[0]);
printf("str2[0]=%c\n",str2[0]);
printf("str1=%p\n",str1);
printf("str2=%p\n",str2);
printf("str1 and str2 are not same\n");
}
if(str3 ==str4){
printf("str3=%p\n",str3);
printf("str4=%p\n",str4);
printf("str3 and str4 are same\n");
}
else{
printf("str3 and str4 are not same\n");
}
return 0;
}
打印:
str1[0]=h
str2[0]=h
str1=0x7ffcc87b0a80
str2=0x7ffcc87b0a90
str1 and str2 are not same
str3=0x7ffcc87b0111
str4=0x7ffcc87b0111
str3 and str4 are same
2、解析
仔细看发现str1=0x7ffcc87b0a8
0和str2=0x7ffcc87b0a9
0地址是不同的,常量字符串去初始化不同的数组的时候就会开辟出不同的内存块,此时地址已经不一样了,如果是对指针初始化,实际会指向同一块常量字符串内存,地址是一样的