c语言动态数组扩容

发布于:2025-08-29 ⋅ 阅读:(13) ⋅ 点赞:(0)

一维数组扩容:

#include <stdlib.h>

// 1维数组扩容。array_ptr为一维数组的指针
void expand_int_array(int** array_ptr, int old_size, int new_size) {
	int* new_array = (int*)malloc(new_size * sizeof(int));
	if (!new_array) {
		fprintf(stderr, "内存分配失败\n");
		return;
	}
	memset(new_array, 0, new_size * sizeof(int));
	if (*array_ptr) {
		memcpy(new_array, *array_ptr, old_size * sizeof(int));
		free(*array_ptr);
	}
	*array_ptr = new_array; // 修改调用者的指针
}

测试代码:

void testExpandArray() {
	// 测试一维数组扩容
	int* arr = (int*)malloc(4 * sizeof(int));
	if (!arr) return;
	arr[0] = 9;
	arr[1] = 5;
	arr[2] = 2;
	arr[3] = 7;
	expand_int_array(&arr, 4, 8);
	printArr1(arr, 8);
}

运行结果:

ok. 

二维数组扩容:

// 扩容二维数组arr_ptr为二维数组的指针
void expand_2d_array(int*** arr_ptr, int* current_capacity, int new_capacity, int* column_sizes) {
	if (new_capacity <= *current_capacity) {
		printf("新容量必须大于当前容量\n");
		return;
	}

	int** new_arr = (int**)malloc(new_capacity * sizeof(int*));
	if (!new_arr) {
		perror("内存分配失败");
		return;
	}

	// 复制原有行数据
	for (int i = 0; i < *current_capacity; i++) {
		new_arr[i] = (*arr_ptr)[i];
	}

	// 初始化新增行(每行列数由column_sizes指定)
	for (int i = *current_capacity; i < new_capacity; i++) {
		new_arr[i] = (int*)malloc(column_sizes[i] * sizeof(int));
		if (!new_arr[i]) {
			perror("行内存分配失败");
			return;
		}
		memset(new_arr[i], 0, column_sizes[i] * sizeof(int));
	}

	free(*arr_ptr); // 原有的释放掉
	*arr_ptr = new_arr;
	*current_capacity = new_capacity;
}

测试代码:

void testExpandArray2() {
	// 测试二维数组扩容
	int capacity = 3;
	int** arr = (int**)malloc(capacity * sizeof(int*));
	if (!arr) return;
	int column_sizes[] = { 2, 3, 1 }; // 初始每行的列数

	// 初始化原始数组
	for (int i = 0; i < capacity; i++) {
		arr[i] = (int*)malloc(column_sizes[i] * sizeof(int));
		if (!arr[i]) return;
		for (int j = 0; j < column_sizes[i]; j++) {
			arr[i][j] = j;
		}
	}

	// 准备扩容参数
	int new_capacity = 5;
	int new_column_sizes[] = { 2, 3, 1, 4, 2 }; // 包含原有行和新增行的列数. 
	expand_2d_array(&arr, &capacity, new_capacity, new_column_sizes);
	printArr2(arr, new_capacity, new_column_sizes);
}

void printArr2(int** arr, int size, int* returnColumnSizes) { // 打印二维数组
	printf("[");
	int isFirst = 1;
	for (int i = 0; i < size; i++) {
		if (isFirst) {
			isFirst = false;
		}
		else {
			printf(",");
		}
		int isSubFirst = 1;
		printf("[");
		for (int j = 0; j < returnColumnSizes[i]; j++) {
			if (isSubFirst) {
				isSubFirst = false;
			}
			else {
				printf(",");
			}
			printf("%d", arr[i][j]);
		}
		printf("]");
	}
	printf("]\n");
}

void printArr1(int* arr, int size) // 打印一维数组
{
	printf("[");
	int isFirst = 1;
	for (int i = 0; i < size; i++) {
		if (isFirst) {
			isFirst = false;
		}
		else {
			printf(",");
		}
		printf("%d", arr[i]);
	}
	printf("]\n");
}

运行结果:

ok.  另外,也可以利用realloc函数实现动态数组扩容。代码略。


网站公告

今日签到

点亮在社区的每一天
去签到