简体   繁体   English

如何转置数组但不更改 c 中的行数和列数?

[英]How to transpose an array but without changing the number of rows and columns in c?

I have recently encountered a problem in 2d array for which I am not able to get right solution.我最近在二维数组中遇到了一个问题,我无法得到正确的解决方案。 There's an array like:有一个数组,如:

    1,4,7,10,
    2,5,8,11,
    3,6,9,12

And I want it to be like:我希望它像:

    1,2,3,4,
    5,6,7,8,
    9,10,11,12

Heres a code snippet that I have written:这是我编写的代码片段:

#include <stdio.h>    
int main ()    
{    
    
    int arr[3][4]={
        {1,4,7,10},
        {2,5,8,11},
        {3,6,9,12}
    };     
    
    int i,j;
    
    for(i=0;i<3;i++)
    {
        for(j=0;j<4;j++)
        {
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    
    printf("\n\n");
    int copy[3][4];
    int temp[3][4];
    
    for(i=0;i<3;i++)
    {
        for(j=0;j<4;j++)
        {
           copy[][]
        }
        
    }
    
    for(i=0;i<3;i++)
    {
        for(j=0;j<4;j++)
        {
            printf("%d ",copy[i][j]);
        }
        printf("\n");
    }
    return 0;
}    

The matrix矩阵

    1,4,7,10,
    2,5,8,11,
    3,6,9,12

can be written as可以写成

0*3+1, 1*3+1, 2*3+1, 3*3+1
0*3+2, 1*3+2, 2*3+2, 3*3+2
0*3+3, 1*3+3, 2*3+3, 3*3+3

On the other hand, the matrix另一方面,矩阵

    1,2,3,4,
    5,6,7,8,
    9,10,11,12

can be written as可以写成

0*4+1, 0*4+2, 0*4+3, 0*4+4
1*4+1, 1*4+2, 1*4+3, 1*4+4
2*4+1, 2*4+2, 2*4+3, 2*4+4

Now it seems clearer.现在似乎更清楚了。 Then calculate the source and desitination coordinates and do assignments.然后计算源和目的地坐标并进行分配。

for(i=0;i<4*3;i++)
{
    int src_y=i%3, src_x=i/3, dst_y=i/4, dst_x=i%4;
    copy[dst_y][dst_x]=arr[src_y][src_x];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM