字符串介绍


一、字符串

  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 指向的是同一个地址。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值