为了节省内存,C/C++把常量字符串放到单独的一个内存区域。当几个指针赋值给相同的常量字符串时,它们实际上会指向相同的内存地址。但用产量初始化字符数组,结果却不同。
下面是一个小程序示例:
1 #include<stdio.h> 2 int 3 main(void) 4 { 5 char str1[]="hello world"; 6 char str2[]="hello world"; 7 char* str3="hello world"; 8 char* str4="hello world"; 9 if(str1==str2) 10 printf("str1 and str2 are same. "); 11 else 12 printf("str1 and str2 are not same. "); 13 if(str3==str4) 14 printf("str3 and str4 are same. "); 15 else 16 printf("str3 and str4 are not same. "); 17 printf("str1:%d ",(int)str1); 18 printf("str2:%d ",(int)str2); 19 printf("str3:%d ",(int)str3); 20 printf("str4:%d ",(int)str4); 21 return 0; 22 }
运行结果是:
从结果中可以看出,str1和str2是两个字符串数组,我们会为它们分配两个数组内存空间,并将内同复制到数组中去。str3和str4是两个指针,我们无需为它们分配内存空间,只需要将它们重定向到常量字符串在内存中的地址。
另外,从地址值可以看出,常量字符串所在的内存区域是单独划分的,与字符串数组的不同。