1、字符串面试题
下面的代码输出结果是什么?
int main(){ char str1[] = "hwl"; char str2[] = "hwl"; char *str3 = "hwl"; char *str4 = "hwl"; string str5 = "hwl"; string str6 = "hwl"; if (str1 == str2) { cout<<"1 == 2"<<endl; } else { cout<<"1 != 2"<<endl; } if (str3 == str4) { cout<<"3 == 4"<<endl; } else { cout<<"3 != 4"<<endl; } if (str5 == str6) { cout<<"5 == 6"<<endl; } else { cout<<"5 != 6"<<endl; } system("pause"); return 0; }
为了节省内存C/C++把常量字符单独放进一个内存区域。当几个指针复制给相同的常量字符串时,他们实际上会指向相同的地址。
运行结果:1 != 2(分配两个内存,把字符串复制进去,两个初始地址不同的字符数组,所以1 != 2)
3 == 4 (地址相同)
5 == 6(内容相同)
原文:http://blog.csdn.net/h_wlyfw/article/details/20943619