一、字符串
C/C++中每个字符串都以字符’\0’作为结尾,这样我们就能很方便地找到字符串的最后尾部。但由于这个特点,每个字符串中都有一个额外字符的开销,稍不留神就会造成字符串的越界。
二、问题和答案
1.面试题
代码如下(示例):
int _tmain(int argc, _TCHAR* argv[])
{
char str1[] = "hello world";
char str2[] = "hello world";
char* str3 = "hello world";
char* str4 = "hello world";
if (str1 == str2)
printf("str1 and str2 are same.\n");
else
printf("str1 and str2 are not same.\n");
if (str3 == str4)
pirntf("str3 and str4 are same.\n");
else
printf("str3 and str4 are not same.\n");
return 0;
}
2.答案
输出的第一行是"str1 and str2 are not same."
输出的第二行是"str3 and str4 are same."
总结
str1 和str2 是两个字符串,我们会为它们分配两个长度为12字节的空间,并把"hello world"的内容分别赋值到数组中去。这是两个初始地址不同的数组,因此str1 和 str2的指也不相同。
str3和str4是两个指针,我们无须为它们分配以储存字符串的内容,而只需要把它们指向"hello world"是常量字符串,它在内存中只有一个拷贝,因此str3 和 str4 指向的是同一个地址。