table of Contents
Pointer array
Pointer array: is an array, each element of which is a pointer.
Definition method:int* p[10];
Array pointer
Array pointer: is a pointer that points to an array.
Definition method:int(*p)[10];
&Array name and array name
arr is the array name, and the array name represents the address of the first element of the array.
int arr[10]={
0};
int(*p)[10]=&arr;
int(*p)[10]=arr;
So what is &arr?
Let's first look at a piece of code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[10] = {
0 };
printf("%p\n", arr);
printf("%p\n", &arr);
system("pause");
return 0;
}
Result: As
you can see, the address printed by the array name and & array name is the same. Are the two the same?
Let's look at a piece of code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[10] = {
0 };
printf("arr = %p\n", arr);
printf("&arr= %p\n", &arr);
printf("arr+1 = %p\n", arr + 1);
printf("&arr+1= %p\n", &arr + 1);
system("pause");
return 0;
}
According to the above code, we find that in fact & arr and arr, although the value is the same, the meaning should be different.
In fact: &arr represents the address of the array, not the address of the first element of the array. The address of the array +1, skip the size of the entire array, so the difference between &arr+1 and &arr is 40.
Use of array pointers
In the following code example: the
array name arr represents the address of the first element. The first element of the two-dimensional array is the first row of the two-dimensional array. So the arr passed here is equivalent to the address of the first row, which is a one-dimensional array, which can be accepted by an array pointer.
#include <stdio.h>
#include <stdlib.h>
void print_arr1(int arr[3][4], int row, int col){
int i = 0;
for (i = 0; i < row; i++){
for (int j = 0; j < col; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void print_arr2(int (*arr)[4], int row, int col){
int i = 0;
for (i = 0; i < row; i++){
for (int j = 0; j < col; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[3][4] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12 };
print_arr1(arr, 3, 4);
print_arr2(arr, 3, 4);
//数组名arr表示首元素的地址
//二维数组的首元素是二维数组的第一行
//所以这里传递的arr相当于第一行的地址,是一个一维数组
//可以用数组指针来接受
system("pause");
return 0;
}
Array names are implicitly converted to pointers
In C language, the name of the array is used as the parameter of the function, which is essentially the transfer of the address. The first address of the array is passed to the formal parameter. The formal parameter and the actual parameter share the same storage space. The change of the formal parameter is the change of the actual parameter.
If it is one int p[5]
, the type of p is int *
.
If it is one int p[3][5]
, the type of p is int(*)[5]
.
If it is one int p[3][4][5]
, the type of p is int( * )[4][5]
.