如何在运行时缩小struct matrix结构体(使用realloc()实现)
如何对Matrix结构体存储的向量缩容(保留前两个元素)
我定义了一个Matrix结构体来存储1行3列的向量(元素为1、2、3),想要缩容这个向量,只保留前两个元素并移除第三个元素3。尝试用realloc()实现但没成功,期望的输出是:
1 2 3 1 2
初始代码
#include <stdio.h> #include <stdlib.h> typedef struct { size_t nrows, ncols; size_t *array; } Matrix ; int ncol = 3; int nrow = 1; void print_matrix(Matrix * matrix); int main() { Matrix *mat1 = (Matrix *) malloc(sizeof(Matrix)); mat1->nrows = nrow; mat1->ncols = ncol; mat1->array = (size_t *) malloc(mat1->nrows * mat1->ncols * sizeof(int)); mat1->array[0 * ncol + 0] = 1; mat1->array[0 * ncol + 1] = 2; mat1->array[0 * ncol + 2] = 3; print_matrix(mat1); mat1->nrows = mat1->nrows - 1; mat1->array = (size_t *) realloc(mat1, nrow * ncol * sizeof(int)); print_matrix(mat1); free(mat1); } void print_matrix(Matrix * matrix) { for (size_t row =0; row<matrix->nrows; row++) { for (size_t col =0; col<matrix->ncols; col++) { printf("%zu ", matrix->array[row * ncol + col]); } printf("\n"); } }
原代码的问题
- 缩容逻辑错误:要保留前两个元素,应该修改结构体的
ncols(列数)而非nrows(行数),因为向量是1行3列,缩容后是1行2列。 realloc使用错误:原代码错误地将结构体指针mat1传给realloc,实际需要重新分配内存的是存储元素的数组指针mat1->array。- 内存分配类型不匹配:
array是size_t*类型,分配时用了sizeof(int),应该改为sizeof(size_t)或者更安全的sizeof(*mat1->array)。 - 缺少内存分配失败检查:
malloc和realloc都可能返回NULL,未做错误处理会导致程序崩溃。 - 索引计算依赖全局变量:
print_matrix中用全局变量ncol计算数组索引,缩容后全局变量未更新,会导致索引计算错误。
修正后的代码
#include <stdio.h> #include <stdlib.h> typedef struct { size_t nrows, ncols; size_t *array; } Matrix ; int ncol = 3; int nrow = 1; void print_matrix(Matrix * matrix); int main() { Matrix *mat1 = (Matrix *) malloc(sizeof(Matrix)); if (mat1 == NULL) { printf("无法分配内存\n"); exit(EXIT_FAILURE); } mat1->nrows = nrow; mat1->ncols = ncol; mat1->array = (size_t *) malloc(mat1->nrows * mat1->ncols * sizeof(*mat1->array)); if (mat1->array == NULL) { printf("无法分配内存\n"); free(mat1); exit(EXIT_FAILURE); } // 初始化向量元素 mat1->array[0 * mat1->ncols + 0] = 1; mat1->array[0 * mat1->ncols + 1] = 2; mat1->array[0 * mat1->ncols + 2] = 3; print_matrix(mat1); // 执行缩容操作:列数减1,重新分配数组内存 mat1->ncols -= 1; size_t* new_array = (size_t *) realloc(mat1->array, mat1->nrows * mat1->ncols * sizeof(*mat1->array)); if (new_array == NULL) { printf("无法重新分配内存\n"); free(mat1->array); free(mat1); exit(EXIT_FAILURE); } mat1->array = new_array; print_matrix(mat1); // 释放所有分配的内存 free(mat1->array); free(mat1); } void print_matrix(Matrix * matrix) { for (size_t row = 0; row < matrix->nrows; row++) { for (size_t col = 0; col < matrix->ncols; col++) { // 使用结构体自身的ncols计算索引,避免全局变量干扰 printf("%zu ", matrix->array[row * matrix->ncols + col]); } printf("\n"); } }
内容的提问来源于stack exchange,提问作者ecjb
相关产品推荐
相关产品推荐

