一道 c++字符串 面试题

本文探讨了C/C++中字符串的内存管理方式,包括如何使用“”作为结束符,以及如何通过将常量字符串存储在独立的内存区域来节省内存。详细解释了字符数组和指针在处理相同字符串时的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c/c++ 中的字符串以“\0”作为结尾符,这样每个字符串都有一个额外字符的开销。下面代码将造成内存越界。

char str[10];
strcpy(str, “0123456789”);

为了节省内存,c/c++ 会把常量字符串放到单独的一个内存区域。当几个指针赋予相同的常量字符串时,它们实际上会指向相同的内存地址。

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)
    printf("str3 and str4 are same.\n");
else
    printf("str3 and str4 are not same.\n");

str1和str2是两个字符数组,它们分别占据12个字节的空间,并且分别保存着“hello world”。这是两个起始地址不同的数组,因此str1与str2不相等。第一行输出“str1 and str2 are not same.”。

str3和str4是两个指针,上面已经说到,像这样两个指针赋予相同的常量字符串时,c/c++ 会把常量字符串放到单独的一个内存区域,并且它们都会指向这个相同的内存地址,常量字符串“hello world”在内存中只有一个拷贝。所以str3和str4相等,第二行输出“str3 and str4 are same.”。

【学习资料】 《剑指offer》

转载于:https://www.cnblogs.com/zhuyf87/archive/2013/03/07/2947555.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值