How is a two-dimensional array created in the C language?

In the C language, you can create a two-dimensional array using the following methods:

  1. Create a two-dimensional array using a static method.
数据类型 数组名称[行数][列数];

This method determines the size of the array at compile time, for example:

int arr[3][4];  // 创建一个3行4列的整型数组
  1. Create a two-dimensional array using a dynamic approach.
数据类型 **数组名称;
数组名称 = (数据类型 **)malloc(行数 * sizeof(数据类型 *));
for (int i = 0; i < 行数; i++) {
    数组名称[i] = (数据类型 *)malloc(列数 * sizeof(数据类型));
}

This method allows for dynamically allocating the size of an array at runtime, for example:

int **arr;
arr = (int **)malloc(3 * sizeof(int *));
for (int i = 0; i < 3; i++) {
    arr[i] = (int *)malloc(4 * sizeof(int));
}
  1. Create a two-dimensional array using array pointers.
数据类型 (*数组名称)[列数];
数组名称 = (数据类型 (*)[列数])malloc(行数 * 列数 * sizeof(数据类型));

This approach treats a 2D array as a 1D array and accesses it through pointers, for example:

int (*arr)[4];
arr = (int (*)[4])malloc(3 * 4 * sizeof(int));

It is important to note that after using a dynamically created 2D array, you need to use the free() function to release memory to prevent memory leaks.

广告
Closing in 10 seconds
bannerAds