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

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转置后的数组就会出现错误,不知道为什么啊。。。跪求大佬帮我看看哪里出现错误了?

https://img1.mukewang.com/5ac970590001164d06080377.jpg

https://img1.mukewang.com/5ac96fc0000105b414150396.jpg

Single丶love
浏览 1282回答 1
1回答

慕设计7118955

Matrix Transpose_Mat(Matrix mat) 这个函数第六行target->data[i] = (int *)malloc(sizeof(target->col));改成target->data[i] = (int *)malloc(sizeof(int)*target->col);
打开App,查看更多内容
随时随地看视频慕课网APP