Array pointer
Why sometimes we need to define a pointer to an array instead of an array element? How to define it?
Answer and analysis:
The pointer is used to save the address of an element and take advantage of its unique advantages. Therefore, when an element needs to be an array, the pointer to an array must be used, for example, a multi-dimensional array needs to be dynamically generated in high dimensions.
Example: int (* pelement) [2].
The following is an example:
Int array [2] [3] = {1, 2, 3}, {4, 5, 6 }}; INT (* pA) [3]; // defines a pointer to an array Pa = & array [0]; // The '&' symbol can reflect the meaning of PA, indicating that it is a pointer to an array Printf ("% d", (* pA) [0]); // print array [0] [0], that is, 1 Pa ++; // guess who it points? Array [1]? Right! Printf ("% d", (* pA) [0]); // print array [1] [0], that is, 4 |
The preceding example fully illustrates the definition and usage of an array pointer that points to the entire array.
It should be noted that, as we have discussed in the fourth article, the pointer step refers to the size of the object referred to in it. Therefore, PA ++ moves the entire size of an array backward, instead of moving the size of an array element backward.
Pointer Array
As defined below:
Struct ut_test_struct * PTO [2] [max_num]; |
Analyze the meaning of this definition and try to explain what are the possible advantages of this definition?
Answer and analysis:
We have discussed the array pointer before, and now we have mentioned the pointer array. The two forms are very similar. So how can we distinguish between the two definitions? The analysis is as follows:
The array pointer is a pointer to an array, for example, INT (* pA) [5].
Pointer array: An array composed of pointers, such as int * pa [5].
As for the advantages of the above pointer array, there are roughly two common reasons:
A) the pointer content can be dynamically generated as needed to avoid space waste.
B) The pointers are arranged in arrays, making indexing very convenient.
In actual programming, selecting to use a pointer array mostly requires the above two benefits.
Code:
# Include <cstdio>
Int _ Inc (int I) // an array pointer is used to add 1.
{
Char (* P) [2] = (char (*) [2]) I;
Return (INT) & (* P) [1]);
}
Int main ()
{
Int r = 1;
Int * w = & R;
W [0] = 7;
Printf ("% d \ n", W [0]);
Char C [2];
C [0] = 'a ';
C [1] = 'B ';
Char (* A) [2] = & C;
Printf ("% d \ n", _ Inc (2147483646 ));
Return 0;
}