How to use pointers to two-dimensional arrays in the C …

In the C language, two-dimensional arrays can be accessed and manipulated using pointers. It is important to note that a pointer to a two-dimensional array is actually a pointer to a pointer.

Here are some common operations examples using a two-dimensional array pointer:

  1. Declare and initialize a pointer to a two-dimensional array.
int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int (*ptr)[4];  // 定义一个指向包含4个元素的一维数组的指针
ptr = arr;  // 将指针指向二维数组的第一行
  1. Accessing array elements through a two-dimensional array pointer.
int value = ptr[1][2];  // 访问第二行第三列的元素,即7
  1. Traverse a two-dimensional array using pointer arithmetic.
int i, j;
for (i = 0; i < 3; i++) {
    for (j = 0; j < 4; j++) {
        printf("%d ", *(*(ptr + i) + j));  // 输出二维数组的所有元素
    }
    printf("\n");
}
  1. Passing a two-dimensional array to a function using pointers.
void printArray(int (*arr)[4], int rows, int cols) {
    int i, j;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; 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}};
    printArray(arr, 3, 4);
    return 0;
}

I hope the examples above can help you understand and utilize pointers to two-dimensional arrays in the C language.

bannerAds