为了账号安全,请及时绑定邮箱和手机立即绑定

关于c语言动态分配二维数组free的错误求dalao看看怎么回事谢谢啊~~~~

关于c语言动态分配二维数组free的错误求dalao看看怎么回事谢谢啊~~~~

C
Single丶love 2018-04-08 09:29:57
typedef struct { int**data; int row; int col;}MyMatrix;typedef MyMatrix* Matrix;/*编写矩阵输入函数 INPUT_MAT,通过该函数完成矩阵的输入并返回保存矩阵的数组和对应矩阵的行数、列数。(不能使用全局变量)*/Matrix INPUT_MAT() { int m_row, m_col; printf("输入要创建的矩阵的行数和列数:"); scanf("%d%d", &m_row, &m_col); if (m_row <= 0 || m_col <= 0) { printf("输入的行数和列数错误!矩阵创建失败!\n"); return NULL; } Matrix mat = (Matrix)malloc(sizeof(MyMatrix)); mat->row = m_row; mat->col = m_col; mat->data = (int **)malloc(sizeof(int *)*m_row); printf("输入矩阵的元素:\n"); for (int i = 0; i < m_row; i++) { mat->data[i] = (int *)malloc(sizeof(int)*m_col); for (int j = 0; j < m_col; j++) scanf("%d", &mat->data[i][j]); } printf("矩阵创建成功!\n"); return mat;}/*编写矩阵输出函数 OUTPUT_MAT,通过该函数完成矩阵的输出。*/void OUTPUT_MAT(Matrix mat) { printf("矩阵输出如下:\n"); for (int i = 0; i < mat->row; i++) { for (int j = 0; j < mat->col; j++) printf("%d ", mat->data[i][j]); printf("\n"); }}/*清理矩阵*/void Clean_Mat(Matrix mat) { for (int i = 0; i < mat->row; i++) free(mat->data[i]); free(mat->data); free(mat);}/*求矩阵的转置,矩阵的转置 A’=(aji)n×m,转置前输出原矩阵,转置后输出转置矩阵。*/Matrix Transpose_Mat(Matrix mat) { Matrix target = (Matrix)malloc(sizeof(MyMatrix)); target->row = mat->col; target->col = mat->row; target->data = (int**)malloc(sizeof(int*)*target->row); for (int i = 0; i < target->row; i++) target->data[i] = (int *)malloc(sizeof(target->col)); for (int i = 0; i < target->row; i++) for (int j = 0; j < target->col; j++) target->data[i][j] = mat->data[j][i]; return target;}void Transpose_Function() { system("cls"); printf("当前功能:矩阵的转置\n"); Matrix mat = INPUT_MAT(); if (!mat) { int b; do { printf("输入0回到主菜单:"); scanf("%d", &b); } while (b != 0); return; } Matrix target = Transpose_Mat(mat); printf("转置前"); OUTPUT_MAT(mat); printf("转置后"); OUTPUT_MAT(target); int b; do { printf("输入0回到主菜单:"); scanf("%d", &b); } while (b != 0); Clean_Mat(mat); Clean_Mat(target); return;}free原始数组没问题,但是free转置后的数组就会出现错误,不知道为什么啊。。。跪求大佬帮我看看哪里出现错误了?
查看完整描述

1 回答

已采纳
?
慕设计7118955

TA贡献8条经验 获得超2个赞

Matrix Transpose_Mat(Matrix mat) 这个函数第六行target->data[i] = (int *)malloc(sizeof(target->col));
改成target->data[i] = (int *)malloc(sizeof(int)*target->col);

查看完整回答
反对 回复 2018-04-08
  • 1 回答
  • 1 关注
  • 1281 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信