How can you reference a two-dimensional array in the C language?
In C language, pointers can be used to reference two-dimensional arrays. Here are some common methods for referencing two-dimensional arrays:
- Create an array of pointers: Set up an array where each element is a pointer pointing to a one-dimensional array. For example, int *arr[5] represents an array with 5 pointers, each pointing to a one-dimensional array of integers.
- To point to the starting address of a two-dimensional array: Declare a pointer variable and assign it to the starting address of the two-dimensional array. For example, int (*arr)[5] represents a pointer pointing to a one-dimensional array containing 5 elements of type int.
- Using pointer to pointer: declare a variable that points to a pointer, and point it to the first address of a two-dimensional array. For example, int **arr represents a pointer to a pointer to an integer, which can be used to reference a two-dimensional array.
Here is an example code that demonstrates how to reference a two-dimensional array using an array of pointers.
#include <stdio.h>
int main() {
int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int *ptr[3];
// 将每个指针指向一维数组的首地址
for (int i = 0; i < 3; i++) {
ptr[i] = arr[i];
}
// 使用指针数组引用二维数组
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", ptr[i][j]);
}
printf("\n");
}
return 0;
}
When running the example code above, the output will be:
1 2 3 4
5 6 7 8
9 10 11 12
Note: In the code examples above, each row of the two-dimensional array contains 4 elements, so the type of the pointer array is int *ptr[3]. If the number of columns in the two-dimensional array is different, the type and traversal method of the pointer array need to be changed accordingly.