剑指offer笔试题 · 常量字符串
【摘要】
🔥每篇前言
博客主页:安然无虞作者介绍:2021年博客新星Top2咱的口号:🌹小比特,大梦想🌹作者请求:由于博主水平有限,博文中难免会有错误和不准之处,我也非常渴望知道这些错误,恳请...
🔥每篇前言
1.引入:字符指针
在指针类型中我们知道有一种指针类型是char*,它有两种使用方法:
一般使用:
#include<stdio.h>
int main()
{
char ch = 'w';
char* pc = &ch;
*pc = 'a';
printf("%c\n", ch);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
这种使用方法比较简单,我就不过多阐述了,看看下面这种使用方法:
#include<stdio.h>
int main()
{
char* p = "abcdef";
printf("%s\n", p);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
注意上面的 abcdef 是常量字符串,存储在内存的只读数据区(只读不可写)
特别容易让我们以为是把字符串 abcdef 放到字符指针 p 里了,其实本质上是把字符串 abcdef 首字符的地址放到 p 中
所以下面代码是有问题的:
#include<stdio.h>
int main()
{
char* p = "abcdef";
*p = 'w';//目的是将'a'改成'w'(bug)
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
上面的第6行代码是错误的,因为常量字符串不可以修改,所以为避免上述错误,可将第5行代码修改为:
const char* p = "abcdef";
- 1
这样的话就会避免上述错误。
2.剑指offer · 常量字符串面试题
面试题:
#include <stdio.h>
int main()
{
char str1[] = "hello bit.";
char str2[] = "hello bit.";
char* str3 = "hello bit.";
char* str4 = "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");
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
解题思路:
- str1 和 str2 是两个字符数组,数组的操作方式是将右边的常量字符串拷贝到数组的空间中,所以它们是两块空间,只是内容相同,而作为数组名,str1 和 str2 是数组首元素的地址,所以 str1 != str2
- str3 和 str4 是两个字符指针,指向的是同一个常量字符串,而常量字符串存储在单独的一个内存区域(只读数据区),当几个指针指向同一个常量字符串的时候,它们实际上会指向同一块内存
3.遇见安然遇见你,不负代码不负卿。
前段时间博主状态不好,没有及时更新,后面就会慢慢提速咯,感谢大家的支持与陪伴。
文章来源: bit-runout.blog.csdn.net,作者:安然无虞,版权归原作者所有,如需转载,请联系作者。
原文链接:bit-runout.blog.csdn.net/article/details/122970383
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)