c++ - 为什么是这个结果?

标签 c++ pointers

那是关于堆栈的吗?我认为最后一个 *p++ 是未定义的。 *p++ 是指 *(p++) 还是 *p;p++;?

void test123()
{

    char s[] = "123", * p;
    p = s;
    // 1 2 3
    cout << *p++ << endl;
    cout << *p++ << endl;
    cout << *p++ << endl;

}
void test321()
{
    char s[] = "123", * p;
    p = s;
    //321
    cout << *p++ << *p++ << *p++ << endl;

}
int main(void)
{
    cout << "123:" << endl;
    test123();
    cout << "123:" << endl;
    test321();
    cout << "hello world" << endl;
    return 0;
}

我认为结果是未定义的。

最佳答案

*p++ 根据运算符优先级计算为 *(p++)p++ 所做的是将 p 递增 1 并返回递增前的值

来自 https://en.cppreference.com/w/cpp/language/operator_incdec

Post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement.

即使在您提到的最后一行,p++ 也会返回位置 s+2,因此取消引用它我们得到 3,而不是下一个地址

除了评估的顺序(在test321),这段代码没有未定义的行为。

% 如果表达式是 *++p 它会完全按照你说的去做(但是它仍然不是未定义的,因为每个字符串文字都以零结尾(\0 ).

关于c++ - 为什么是这个结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338830/

相关文章:

Visual Studio 2012 中的 C++ 单元测试

c++ - 消除低效代码

pointers - 为什么 V8 使用指针标记而不是 NaN 装箱?

c++ - 不明白段错误

c++ - 将新实例或其自身作为 std::shared_ptr 而不是原始指针返回

c++ - vector动态内存分配之private member vector

c++ - 周期约为 100ms 的可移植周期性定时器

C++ 指针数组

c++ - 在没有指针的情况下随时随地获得额外的内存

pointers - 将 *[]foo 类型的变量转换为 *[]bar