使用数组指针进行 Cout 打印 - 奇怪的行为

Cout printing with array pointers - weird behavior

我一直在玩指针,得到了我没想到的结果:

#include <iostream>
#include <vector>

int main() {
    int arr[4] = { 1, 2, 3, 4 };
    int* pArr = arr;
    std::cout << "First number: " << *pArr << " at address: " << pArr;
    pArr++;
    std::cout << "\nSecond number: " << *pArr << " at address: " << pArr;
    pArr++;
    std::cout << "\nThird number: " << *pArr << " at address: " << pArr;
    pArr++;
    std::cout << "\nFourth number: " << *pArr << " at address: " << pArr;
    
    int* pArr2 = arr;
    std::cout << "\n"
        << *pArr2++ << "\n"
        << *pArr2++ << "\n"
        << *pArr2++ << "\n"
        << *pArr2++ << "\n";
    /*
    int* pArr2 = arr;
    std::cout << "\n"
        << ++ * pArr2 << "\n"
        <<  * ++pArr2 << "\n";
    */
}

两个不同的结果:

1 2 3 4 - 正如预期的那样使用第一种方法

4 3 2 1 - 使用带有多个参数的 cout 我不知道正确的名称.

所以我的问题是 - 为什么会发生这种情况?使用多个 cout 语句会产生预期的 for me 代码,而仅使用 1 个 cout 会产生向后的解决方案。

作为旁注,另一个让我感到困惑的事情是预增量导致所有值都相等。在代码的注释位中,结果是 3 3,无论 ++ 相对于 *.

的位置如何

此代码:

std::cout << "\n" << *pArr2++ << "\n";
std::cout << "\n" << *pArr2++ << "\n";

pArr 有明确定义的修改顺序,并将打印

1
2

但是这段代码:

std::cout << "\n" << *pArr2++ << "\n" << *pArr2++ << "\n";

在 c++17 之前调用未定义的行为,因为对 pArr2 有多个未排序的修改。该程序有UB,所以它可以打印任何东西。

从c++17开始,修改之间有一个序列点,上面的代码保证打印:

1
2