This is a pointer to an int
:
int *p;
┌────┐
│int*│
└────┘
It should point at an int
, something like this:
┌────┐
│int*│
└─┃──┘
▼
┌───┐
│int│
└───┘
This is an array of 100 pointers to int
:
int *p[100];
That is, it gives you 100 pointers.
┌────┬────┬────┬────┬────┬────┬┄
│int*│int*│int*│int*│int*│int*│
└────┴────┴────┴────┴────┴────┴┄
Each pointer should point an int
, perhaps like this:
┌────┬────┬────┬────┬────┬────┬┄
│int*│int*│int*│int*│int*│int*│
└─┃──┴─┃──┴─┃──┴─┃──┴─┃──┴─┃──┴┄
▼ ▼ ▼ ▼ ▼ ▼
┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌┄
│int││int││int││int││int││int││
└───┘└───┘└───┘└───┘└───┘└───┘└┄
Of course, there's no reason they can't all point at the same int
, or whatever.
You may want to use an array of pointers if you want many pointers that you can easily
iterate over. You may, for example, dynamically allocate objects and have each pointer point at a different object:
p[0] = new int(0);
p[1] = new int(0);
// ...
Perhaps dynamically allocating int
s isn't the best example, but I think the point is clear.
This is a pointer to an array of 100 int
:
int (*p)[100];
That is, it gives you just 1 pointer:
┌───────────┐
│int(*)[100]│
└───────────┘
It should point at an array that contains 100 int
s:
┌───────────┐
│int(*)[100]│
└─┃─────────┘
▼
┌───┬───┬───┬───┬───┬───┬┄
│int│int│int│int│int│int│
└───┴───┴───┴───┴───┴───┴┄
You will get a pointer to an array when you use the address-of operator (&
) on the name of an array. For example:
int arr[100] = { /* some initial values */ };
int (*p)[100] = &arr;
Here, I've taken the address of the arr
array, which gives me a pointer to that array. If you then want to access an element of the array, you have to dereference the pointer first: (*p)[3]
will access element 3.
Side note:
Always remember that arrays are not pointers. As we have just seen, we can take the address of an array to get a pointer to it, just like any other (non-temporary) object in C++. The only special connection between arrays and pointers is that the name of an array can be implicitly converted to a pointer to the array's first element. That means the following is valid:
int arr[100] = { /* some initial values */ };
int* p = arr;
The pointer p
will point at the first element in arr
. Note that p
is not a pointer to the array, but a pointer to an element of the array.
(Also note that there is no such thing as an array type function argument. If you write something like int p[]
as a function argument, it is transformed by the compiler to be a int*
.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…