c - 转置二维数组

标签 c

我想转置一个方阵,以下是我的代码。

#include <stdio.h>
#define SIZE 10
void transpose2D(int ar[][SIZE], int rowSize, int colSize);
void display(int ar[][SIZE], int rowSize, int colSize);
int main()
{
  int ar[SIZE][SIZE], rowSize, colSize;
  int i,j;

  printf("Enter row size of the 2D array: \n");
  scanf("%d", &rowSize);
  printf("Enter column size of the 2D array: \n");
  scanf("%d", &colSize);
  printf("Enter the matrix (%dx%d): \n", rowSize, colSize);
  for (i=0; i<rowSize; i++)
    for (j=0; j<colSize; j++)
      scanf("%d", &ar[i][j]);
  printf("transpose2D(): \n");
  transpose2D(ar, rowSize, colSize);
  display(ar, rowSize, colSize);
  return 0;
}
void display(int ar[][SIZE], int rowSize, int colSize)
{
  int l,m;
  for (l = 0; l < rowSize; l++) {
    for (m = 0; m < colSize; m++)
      printf("%d ", ar[l][m]);
    printf("\n");
  }
}
void transpose2D(int ar[][SIZE], int rowSize, int colSize)
{
  int transpose[rowSize][colSize] ;  
  /* We have to define a new transposed array because otherwise, when some of 
   * the values are changed, it wont be an accurate transposition anymore */ 
  int i , j ; 
  /* This function transposes a given 2D matrix */  
  for (i = 0 ; i < rowSize ; i++) {
    for (j = 0 ; j < colSize ; j++) {
      transpose[j][i] = ar[i][j] ; 
    }
  }
  for (i = 0 ; i < rowSize ; i++) { 
    for (j = 0 ; j < colSize ; j++) {
//   ^^^^    ^^^^   ^^^^  ^^^^  ^^^^  
// edit : assign transpose to ar using for loop 
      ar[i][j] = transpose[i][j] ; 
    }
  }
}

给定这样的输入,

Enter row size of the 2D array: 
4
Enter column size of the 2D array: 
4
Enter the matrix (4x4): 
1 2 3 4
1 1 2 2
3 3 4 4
4 5 6 7
transpose2D(): 
1 2 3 4 
1 1 2 2 
3 3 4 4 
4 5 6 7 

这是我得到的结果。但是,我应该得到的是

transpose2D(): 
1 1 3 4
2 1 3 5
3 2 4 6
4 2 4 7

我的代码中是否存在我无法识别的错误? 我的猜测是我的二维数组 transpose[][] 没有正确定义, 但我无法指出任何错误。

非常感谢任何帮助

编辑: 上面的代码现在可以使用突出显示的更改

最佳答案

transpose2D

ar[i][j] = transpose[i][j] ;

在这里,您将 transpose 的越界元素复制到 ar,这可能会引发未定义的行为

您需要启动另一个循环并将 transpose 的元素复制回 ar

关于c - 转置二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312672/

相关文章:

c - 键入 C 时自动添加一个点 (.)

c - 为什么 strlen() 在这些命令行参数以 null 结尾时没有给出正确的长度?

c - C语言中如何将整数转为字符串? (例如 0 => 零)

c - "."和 "->"和有什么区别?

c - 从 GtkEntry 获取属性为 "text"的文本

通过/proc/stat 当前 CPU 核心利用率

c - 位图颜色 - C

python - C通过系统调用执行python脚本

C:亮黄色和亮绿色(ncurses)?

c - System() 参数 C