Pointer knowledge (3): pointer and array, pointer knowledge Array
The concept of arrays is closely related to the concept of pointers. In fact, the array identifier is equivalent to the address of its first element, for example, int a [5]. array name a points to the address of its first element a [0.
The statement is as follows:
The following values are valid:
p = a;
Here, pointers p and a are equivalent. They have the same attributes. The only difference is that we can assign other values to the pointer p, a always points to the first of the five defined integer groups. Therefore, p is just a common pointer variable. In contrast, a is a constant pointer, And the array name is indeed a pointer constant. Therefore, although the previous value assignment expression is valid, the following is not:
a = p;
Because a is an array (pointer constant), constant identifiers cannot be assigned other values.
Due to the characteristics of variables, all expressions containing pointers in the following example are valid:
# Include <iostream> Using namespace std; Int main () { Int a [5]; Int * p; P = a; // p is the address of a [0], because a points to the first address of a, that is, to a [0], * P = 10; // a [0] = 10 P ++; * P = 20; // a [1] = 20 P = & a [2]; * P = 30; // a [2] = 30; P = a + 3; * P = 40; // a [3] = 40 P =; * (P + 4) = 50; // a [4] = 50 For (int n = 0; n <5; n ++) { Cout <a [n] <","; } Cout <'\ n '; } |
Output:10, 20, 30, 40, 50, |
Brackets [] indicate the index of the array element to be referenced ). Brackets [] are also called the offset operator. It is equivalent to adding a number in brackets to the address in the pointer.
For example, the following two expressions are equivalent to each other:
A [5] = 0; // a [offset of 5] = 0
* (A + 5) = 0; // pointed by (a + 5) = 0
Whether a is a pointer or an array name, these two expressions are valid.