Although I always know their two differences, but not the name should be called which. Here's the difference.
Pointer Array (array of pointers)
As the name implies: This is the array, the elements inside the arrays are pointers.
int*arr[10];
This is equivalent to int *(a[4])
because *
the priority is relatively low, so when there is no parenthesis, it is arr和[10]
first combined, into an array, and then the element of this array is an integer pointer.
Initialization
This initialization is to be in the form of an array.
forint010; i++){ a[i] = (int *)malloc5sizeof(int) );}
This is to iterate through each array of elements, to the pointer request space, each pointer to a 5 int
-size memory.
This time, you will be able to assign a value.
fori0i10i++){ for (int j = 0; j < 5; j++){ a[i][j] = 0; }}
At this point, all the elements are assigned a value of 0.
Note: Because each element of the array is a pointer. So you won't get an error when you visit a[0][6]
. But the value of the output is undefined and more dangerous.
Array pointer (a pointer to an array)
This means I'm a pointer, and the pointer points to an array.
int (*arr)[10];
Here let *和arr
's combine to be a pointer, this pointer points to a int
type of array with 10 elements.
Initialization
For the initialization of this I personally think it is relatively difficult to understand.
The first method of initialization:
inttemp[4][Ten] = {};//Method 1int(*arr) [Ten] = temp;//Correct//Method 2int(*Array)[Ten];Array= temp;//Correct//Method 3int(*array_m) [ One], (*array_n) [9];array_m = temp;//ErrorArray_n = temp;//error//Method 4 for(inti =0; I <4; i++) {arr = &temp[i];//Correctarr++;} Arr-= i;//must subtract I to return to the initial position.
Here only Method 1, 2, 4 is correct, 3 inside the two will error.
Here's how to focus on method 4. Why do arr++
you receive the next int [10]
one directly, because it is a pointer to arr
an array, that is int [10]
, when it arr++
moves forward 10 of the length of an int's memory.
Summarize
The above is the difference. I usually use only pointer arrays in a two-dimensional array and seldom use array pointers.
Because the pointer array is better understood, but we should pay attention to the boundary problem.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + Learning-array pointers/pointers arrays