c++ - 关于指针算术和字符串的问题
问题描述
考虑以下程序:
#include <iostream>
using namespace std;
int main()
{
const char* p = "12345";
const char **q = &p;
*q = "abcde";
const char *s = ++p;
p = "XYZWVU";
cout << *++s;
return 0;
}
我已经计算出指针算法,并且我已经计算出s指向p的第三个字符。但是,在执行这个程序时,它会打印 'c'(这是 abcde 的第三个字符)而不是 'Z'。我在这里的疑问是在这条线上
p = "XYZWVU";
我们已经让指针p指向字符串的第一个字符(XYZWVU),那么为什么这个程序不打印'Z'呢?
请指导。
解决方案
#include <iostream>
using namespace std;
int main()
{
const char* p = "12345"; // have p point at "12345"
const char **q = &p; // have q point at p
*q = "abcde"; // change what q points at (p) to "abcde"
const char *s = ++p; // increment p and assign its result ("bcde") to s
p = "XYZWVU"; // have p point at "XYZWVU"
cout << *++s; // increment s and dereference the result ("cde")
return 0;
}
p = "XYZWVU";
是在 的值p
赋值给之后完成的s
,所以不会影响 的值s
。
推荐阅读
- php - 我如何使用laravel显示所有动物是狗的帖子
- python - 将 Iris 数据集的前五个观察值从数字映射到字符串
- python - 从while循环中找到最大值
- keras - 量化感知训练 Google Coral 的对象检测模型
- python - 在 Python tkinter 中的线程之间共享变量
- android - 我面临一个错误在 null 上调用了方法“[]”。接收方:null 尝试调用:[]("postId")
- mysql - Mysql:合并两个具有重叠唯一列的相似表
- javascript - 使用 jest 模拟 axios 请求
- r - 在 R 中第二次出现模式时剪切字符串向量的每个元素
- javascript - bulma框架的下拉javascript