C语言非方阵90度逆时针旋转多次出现异常的问题排查
问题根源分析
你的代码核心问题在于非方阵的转置无法在原矩阵的内存空间中完成,且旋转过程中未更新矩阵的行列维度:
- 当处理
2×3这类行列数不等的矩阵时,原矩阵的内存布局是固定的2行×3列。你的transpose函数中,当i=0、j≥2时,matrix[j][i]会访问超出原矩阵范围的内存(原矩阵只有2行,j=2属于越界访问),这会触发未定义行为,导致内存中的垃圾值被写入矩阵。 - 每次逆时针旋转90度后,矩阵的行列数会互换(比如
2×3旋转后变为3×2),但你始终使用初始的row和column值进行操作,后续的反转和打印逻辑全部基于错误的维度执行。
修复方案
解决思路是:每次旋转时,创建一个临时矩阵存储旋转后的结果(维度为原矩阵的列数×行数),通过坐标变换完成旋转,再将临时矩阵复制回原矩阵,同时更新行列维度的值。
修改后的完整代码
#include <stdio.h> #include <stdlib.h> int main() { int row, column; scanf("%d %d", &row, &column); // 动态分配二维数组,灵活调整维度并避免栈溢出 int **matrix = (int **)malloc(row * sizeof(int *)); for (int i = 0; i < row; i++) { matrix[i] = (int *)malloc(column * sizeof(int)); for (int j = 0; j < column; j++) { scanf("%d", &matrix[i][j]); } } int rotation_times; scanf("%d", &rotation_times); rotation_times = rotation_times % 4; for (int i = 0; i < rotation_times; i++) { // 旋转后矩阵维度变为 原列数 × 原行数 int new_row = column; int new_col = row; int **temp_matrix = (int **)malloc(new_row * sizeof(int *)); for (int x = 0; x < new_row; x++) { temp_matrix[x] = (int *)malloc(new_col * sizeof(int)); // 逆时针旋转90度的坐标映射:原matrix[i][j] → temp_matrix[column-1-j][i] for (int y = 0; y < new_col; y++) { temp_matrix[x][y] = matrix[y][column - 1 - x]; } } // 释放原矩阵内存 for (int k = 0; k < row; k++) { free(matrix[k]); } free(matrix); // 更新矩阵指针和维度 matrix = temp_matrix; row = new_row; column = new_col; } // 打印结果 for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { printf("%d ", matrix[i][j]); } printf("\n"); free(matrix[i]); } free(matrix); return 0; }
关键说明
- 坐标变换逻辑:逆时针旋转90度时,原矩阵中位置
(i,j)的元素会移动到新矩阵的(column-1-j, i)位置(针对原矩阵row×column,新矩阵为column×row)。 - 动态内存分配:替代变长数组,避免大矩阵导致的栈溢出,同时支持旋转后灵活调整矩阵维度。
- 维度更新:每次旋转后同步更新
row和column的值,确保后续操作基于正确的矩阵维度执行。
测试你的输入:
2 3 1 1 1 2 3 4 2
输出将符合预期:
4 3 2 1 1 1
内容的提问来源于stack exchange,提问作者TheRealF6
相关产品推荐
相关产品推荐

