指向 10 个数组的指针 ints 意味着指向 10 个元素的数组,不多也不少,或者如果您有一个二维数组,则指向此类数组的给定行,前提是它正好有 10 列。
指向int、int *ptr[10] 的指针数组就是这样,它有10 个指向int 的指针,每个指针都可以分配int 的地址,它可以是数组的一部分与否。
示例 1:
int (*ptr)[10];
int arr[10];
ptr = &arr; //correct, arr has 10 elements
int arr2[12];
ptr = &arr2; //not correct, arr2 does not have 10 elements
此类指针可用于指向行数不定但列数固定的二维数组。
示例 2:
int arr[5][10];
ptr = arr; //correct, pointer to the 1st row of a 2D array with 10 cols
ptr++; //now points to the second row
int arr2[5][12];
ptr = arr2; //not correct, incompatible pointer, has too many cols
示例 3:
int(*ptr)[3];
int arr[2][3] = {{1, 2, 3}, {4, 5, 7}};
ptr = arr;
printf("%d", ptr[1][2]); //array indexing is identical as using arr[1][2]
指针数组与指向数组的指针
当需要动态分配/释放内存时,数组指针的优势就出现了:
以 4 行 5 列的二维数组为例:
int (*ptr)[5];
ptr = calloc(5, sizeof *ptr); //simple assignment
free(ptr); //simple deallocation
int *ptr[5];
for (int i = 0; i < 5; i++) //each pointer needs it's own allocation
ptr[i] = calloc(5, sizeof **ptr);
for (int i = 0; i < 5; i++) //each pointer needs to be freed
free(ptr[i]);
另一方面,如果你有一个指针数组,你可以有一个 uneven 数组,也就是说第一行可以有 10 个ints,但第二行可以有 20 个:
int *ptr[5];
for (int i = 0; i < 5; i++)
ptr[i] = calloc( i + 1, sizeof **ptr);
在上面的示例中,二维数组的第一行空间为 1 int,第二行空间为 2,第三行空间为 3,依此类推。