admin 发表于 2024-1-11 22:33:03

数组名不可自增与自减

```
#include <iostream>

int main() {
    using namespace std;
    double wages = { 10000.0, 20000.0, 30000.0 };
    double* pw =wages;
    cout << "pw = " << pw << ", *pw = " << *pw << endl;
    pw = pw + 1;
    cout << "pw + 1 = " << pw << ", *(pw + 1) = " << *pw << endl;
    cout << "wages + 1 = " << wages + 1 << ", *(wages + 1) = " << *(wages + 1) << endl;
    //wages = wages + 1;// invalid, because wages is a const pointer
    cout << "wages = " << wages << ", *wages = " << *wages << endl;

    return 0;
}
```

---

Yes, in C++, the name of an array is essentially a constant pointer to the first element of the array. This means that while the contents of the array can be modified, the pointer itself (i.e., the address it holds) cannot be changed.

This is why the line `wages = wages + 1;` is commented out in your code and noted as invalid. If you try to compile this line, you would get a compilation error because you're trying to change the address that `wages` points to, which is not allowed.

However, you can create a separate pointer variable and assign it the address of the array (or the address of the first element of the array), and then you can increment or decrement that pointer variable. This is what's happening with the `pw` pointer in your code.

Here's the relevant part of your code:

```cpp
double* pw =wages; // pw is a pointer to the first element of wages
cout << "pw = " << pw << ", *pw = " << *pw << endl;
pw = pw + 1; // incrementing pw is allowed
cout << "pw + 1 = " << pw << ", *(pw + 1) = " << *pw << endl;
```

In this code, `pw` is a pointer that initially points to the first element of the `wages` array. The line `pw = pw + 1;` increments the pointer to point to the next element in the array. This is allowed because `pw` is a separate pointer variable, not the array name itself.

admin 发表于 2024-1-11 22:42:29

```
Output:
pw = 0x7ffcc524b510, *pw = 10000
pw + 1 = 0x7ffcc524b518, *(pw + 1) = 20000
wages + 1 = 0x7ffcc524b518, *(wages + 1) = 20000
wages = 0x7ffcc524b510, *wages = 10000
```
页: [1]
查看完整版本: 数组名不可自增与自减