我怎么能将2-d阵列的每一行循环移位两个位置?

时间:2011-08-22 11:48:53

标签: c arrays pointers

首先,我想告诉你我到底想要什么........

如果输入是......

  2  3  4 
  5  6  6
  7  5  4

输出应该是......

 7  5  4
 2  3  4
 5  6  6     /*Each row is shifted circularly left by two positons */

我试过这段代码。根据我的知识(我是C的初学者)并写过这个东西..

 /*To shift row of a 4 * 5 matrix by 2 positons left*/

 #include<stdio.h>

 int main() {

    int a[4][5],i,j,k,(*temp)[5];

    for(i=0;i<=3;i++) {
            for(j=0;j<=4;j++)
                    scanf("%d",*(a+i)+j);
    }


    for (k=1;k<=2;k++) {

            for(i=0;i<=3;i++) {

                    temp = (a+i);   /*I thought that *(a+i) will point to the address           of each row and so I should take it in a variable which is capable of pointing to a row of 5 variables that why TEMP */
                    (a+i) = (a+i+1);
                    (a+i+1) = temp;
            }

    }


     for(i=0;i<=3;i++) {

                   for(j=0;j<=4;j++)
                            printf("%d\t",*(*(a+i)+j));


            printf("\n");

     }


  return 0;

 }

我错在哪里.....请纠正我????

2 个答案:

答案 0 :(得分:1)

  1. 您的示例输出看起来像沿列移位:)
  2. scanf("%d",*(a+i)+j);不是一个好方法,请使用 scanf("%d",&a[i][j]);而不是
  3. 您试图在temp = *(a+i);复制一行,但您只能这样做 在这里复印地址。 temp将指向[i],但不会复制 这是数据。
  4. 以下代码给出 输入

    1 1 1 1 1 
    2 2 2 2 2
    3 3 3 3 3
    4 4 4 4 4
    

    输出

    3   3   3   3   3   
    4   4   4   4   4   
    1   1   1   1   1   
    2   2   2   2   2
    

    我像您的示例一样移动了列并使用了新的数组b而不是temp

    #include<stdio.h>
    
     int main() {
    
        int a[4][5],i,j,b[4][5];
    
        for(i=0;i<=3;i++) {
                for(j=0;j<=4;j++)
                        scanf("%d",(*(a+i)+j));
        }
    
    
        for(i=0;i<=3;i++) 
                for(j=0;j<=4;j++)
                    {
                        *(*(b+i)+j)=*(*(a+((i-2+4)%4))+j);
                    }
    
    
         for(i=0;i<=3;i++) {
                       for(j=0;j<=4;j++)
                                printf("%d\t",*(*(b+i)+j));
                printf("\n");
         }
    
        return 0;
    
    }
    

答案 1 :(得分:0)

虽然您正在驾驶的概念可以起作用(但目前有很多错误)在此上下文中使用指针算法会使代码看起来非常复杂,所以我想知道您为什么不尝试使用数组语法重写它。

例如,您可以像这样编写输出:

for(i=0;i<=3;i++) 
{
   for(j=0;j<=4;j++)
       printf("%d\t",a[i][j]);
    printf("\n");     
}

我认为这是初学者理解的更简单的语法。类似地,行周期/交换在这种形式下更加透明。