首页 > 解决方案 > 关于指针算术和字符串的问题

问题描述

考虑以下程序:

#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'呢?

请指导。

标签: c++pointersdeclarationstring-literalspointer-arithmetic

解决方案


#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


推荐阅读