admin 发表于 2024-1-11 23:54:55

Pointer to an array and Array of pointers

```
#include <iostream>

int main() {
    using namespace std;
    double wages = { 10000.0, 20000.0, 30000.0 };

    double (*ps) = &wages;
    cout << "ps = " << ps << ", *ps = " << **ps << endl;
    ps = ps + 1;
    cout << "ps = " << ps << ", *ps = " << **ps << endl;

    double *ps2 = { &wages, &wages, &wages };
    cout << "ps2 = " << ps2 << ", *ps2 = " << **ps2 << endl;
    *ps2 = *ps2 + 1;
    cout << "ps2 = " << ps2 << ", *ps2 = " << **ps2 << endl;

    double *ps3 =&wages;
    double *ps4 =&wages;
    double *ps5 =&wages;
    double *ps6 = { ps3, ps4, ps5 };
    return 0;
}
```

---

Here's the difference:

1. **Pointer to an array (`ps`)**: This is a pointer that points to an entire array, not just a single element. In your code, `double (*ps) = &wages;` declares `ps` as a pointer to an array of 3 doubles. `ps` points to the entire `wages` array.
2. **Array of pointers (`ps2`)**: This is an array where each element is a pointer. It can be used to create things like an array of strings, or to dynamically allocate memory for each element in the array. In your code, `double *ps2 = { &wages, &wages, &wages };` declares `ps2` as an array of 3 pointers to doubles. Each element of `ps2` is a pointer to a corresponding element in the `wages` array.

So, the main difference is that `ps` (pointer to an array) points to an entire array, while `ps2` (array of pointers) contains individual pointers that can point to different things.

admin 发表于 2024-1-11 23:56:17

```
Output:

ps = 0x7ffc7d6340b0, *ps = 10000
ps = 0x7ffc7d6340c8, *ps = 0
ps2 = 0x7ffc7d6340d0, *ps2 = 10000
ps2 = 0x7ffc7d6340d0, *ps2 = 20000
```
页: [1]
查看完整版本: Pointer to an array and Array of pointers