我是靠谱客的博主 忧郁乐曲,这篇文章主要介绍C/C++——C风格的字符串的指针指向的内存位置问题(易错),现在分享给大家,希望可以做个参考。

首先来看一个问题:

这个是我在帮人刷题时,遇到的一个错误,之前一直没注意,也是对指针的理解不深刻的原因吧,我把它简化了,也就不贴原题的代码。
我刚开始以为的会输出: hello C++
结果输出的却是: hello ediot
下一部分给出问题原因

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> using namespace std; void changeInput(char* input){ input = "hello C++"; } int main(){ char *input = "hello ediot"; changeInput(input); cout << input << endl; return 0; }

输出结果:
这里写图片描述

下面来看看input的地址:

inputChange执行前后,input指向的地址是不变的,因为执行inputChange函数,原意是想改变input指向的地址(即input的值),可是input此时是作为地址的值传递,相当于是复制,而非引用和指针传递,所以才出现了上述奇怪的结果。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream> using namespace std; void changeInput(char* input){ input = "hello C++"; cout << "input address in changeInput:" << &input << endl; } int main(){ char *input = "hello ediot"; cout << "input address before changeInput:" << &input << endl; changeInput(input); cout << "input address after changeInput:" << &input << endl; cout << input << endl; return 0; }

输出结果:
这里写图片描述

再来一个解决办法:

正确传的参数应该是input的地址~

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream> using namespace std; void changeInput(char** input){ char *change = "hello C++"; *input = change; } int main(){ char *input = "hello ediot"; changeInput(&input); cout << input << endl; return 0; }

这里写图片描述

最后

以上就是忧郁乐曲最近收集整理的关于C/C++——C风格的字符串的指针指向的内存位置问题(易错)的全部内容,更多相关C/C++——C风格内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(70)

评论列表共有 0 条评论

立即
投稿
返回
顶部