一、问题
C语言如何实现动态⼆维数组?
二、解答
在C语言中,动态创建二维数组的方法通常是通过动态分配内存来实现的。
方法一:逐行动态分配
首先,创建一个指针数组(即一维数组),其元素为指向整型数据的指针(对应二维数组的每一行)。
然后,使用 malloc 函数为每一行分配内存,使得每一行都能容纳指定数量的列元素。
#include <stdio.h>
#include <stdlib.h>
void free_2d_array(int ***arr, int rows)
{
for (int i = 0; i < rows; ++i)
{
free((*arr)[i]);
}
free(*arr);
}
int **create_2d_array(int rows, int cols)
{
int **arr = (int **)malloc(rows * sizeof(int *));
if (arr == NULL)
{
perror("Failed to allocate memory for row pointers");
return NULL;
}
for (int i = 0; i < rows; ++i)
{
arr[i] = (int *)malloc(cols * sizeof(int));
if (arr[i] == NULL)
{
// 如果某一行内存分配失败,则释放之前分配成功的行内存
for (int k = 0; k < i; ++k)
{
free(arr[k]);
}
free(arr);
perror("Failed to allocate memory for a row of data");
return NULL;
}
}
return arr;
}
int main()
{
int rows = 3, cols = 4;
int **arr = create_2d_array(rows, cols);
// 使用和初始化数组
if (arr != NULL)
{
// ...
// 对 arr[i][j] 进行读写操作
// ...
// 释放内存
free_2d_array(&arr, rows);
}
return 0;
}
方法二:连续内存分配
另一种方法是计算总元素数量,一次性分配足够的内存来存储所有元素,并计算每个元素的偏移量模拟二维数组的访问:
#include <stdio.h>
#include <stdlib.h>
void free_continuous_2d_array(int **arr, int rows, int cols)
{
free(arr);
}
int **create_continuous_2d_array(int rows, int cols)
{
int **arr = (int **)malloc(rows * sizeof(int *) + rows * cols * sizeof(int));
if (arr == NULL)
{
perror("Failed to allocate memory for array");
return NULL;
}
// 创建指向数组每一行的指针
int *data = (int *)(arr + rows);
for (int i = 0; i < rows; ++i)
{
arr[i] = data + i * cols;
}
return arr;
}
int main()
{
int rows = 3, cols = 4;
int **arr = create_continuous_2d_array(rows, cols);
// 使用和初始化数组
if (arr != NULL)
{
// ...
// 对 arr[i][j] 进行读写操作
// ...
// 释放内存
free_continuous_2d_array(arr, rows, cols);
}
return 0;
}
三、总结
动态⼆维数组要动态分配指针数组才能实现。