课上写的一道字符串相关的笔试题,我觉得很有意思,这里分享给大家。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
char str1[] = "hello bit.";
char str2[] = "hello bit.";
const char* str3 = "hello bit.";
const char* str4 = "hello bit.";
char *str5 = "hello bit.";
char *str6 = "hello bit.";
if (str1 == str2)
printf("str1 and str2 are same\n");
else
printf("str1 and str2 are not same\n");
if (str3 == str4)
printf("str3 and str4 are same\n");
else
printf("str3 and str4 are not same\n");
if (str5 == str6)
printf("str5 and str6 are same\n");
else
printf("str5 and str6 are not same\n");
if (str4 == str5)
printf("str4 and str5 are same\n");
else
printf("str4 and str5 are not same\n");
return 0;
}
给大家思考一小会儿,觉得答案是什么呢?
答案:

原来,这⾥str3,str4,str5,str6指向的是同⼀个常量字符串(加不加const都不会影响)。C/C++会把常量字符串存储到单独的⼀个内存区域, 当⼏个指针指向同⼀个字符串的时候,他们实际会指向同⼀块内存。但是⽤相同的常量字符串去初始化不同的数组的时候就会开辟出不同的内存块。所以str1和str2不同,str3,str4,str5,str6相同。
1006

被折叠的 条评论
为什么被折叠?



