如何在C中反转多维数组?

sir*_*exy 2 c arrays multidimensional-array

我需要反转用指针表示法制作的2d数组.

要清楚,如果数组是

A B C D E
F G H I J
K L M N O
Run Code Online (Sandbox Code Playgroud)

我需要:

E D C B A
J I H G F
O N M L K
Run Code Online (Sandbox Code Playgroud)

我的代码到目前为止:

#include <stdio.h>
#include <stdlib.h>
#define HEIGHT 3
#define WIDHT 7

void print (char *imprimir)
{
    int i,j;
    for (i=0;i<HEIGHT;i++)
    {
        for (j=0;j<WIDHT;j++)
        {
            printf ("%2c",*(imprimir+(i*WIDHT)+j));
        }
        printf ("\n");
    }
}

int main()
{
    //FILLING THE ARRAY
    char *array=malloc(WIDHT*HEIGHT);
    int i,j;
    for (i=0;i<HEIGHT;i++)
    {
        for (j=0;j<WIDHT;j++)
        {
            *(array+(i*WIDHT)+j)=(i*WIDHT)+j+'a';
        }
    }
    print (array);  
    //TRYING TO REVERSE IT
    char *tmp=malloc(WIDHT);
    for (i=0;i<HEIGHT;i++)
    {
        for (j=0;j<WIDHT/2;j++);
        {
            *tmp=*(array+(i*WIDHT)+j);
            *(array+(i*WIDHT)+j)=*(array+(i*WIDHT)+(WIDHT-j));
            *(array+(i*WIDHT)+(WIDHT-j))=*tmp;
        }
    }
    printf ("PRINTING RESULT!\n");
    print (array);  
}
Run Code Online (Sandbox Code Playgroud)

mer*_*011 6

你有两个错误.

  1. ;的内部for循环结束时有一个分号,所以循环根本没有运行.
  2. 无论你有什么WIDTH - j,你应该拥有WIDTH - 1 -j,因为最高的指数是WIDTH - 1.

此外,人类不计较拼写,所以我改变WIDHT,以WIDTH在全球范围内提高可读性.

这是固定代码.

#include <stdio.h>
#include <stdlib.h>
#define HEIGHT 3
#define WIDTH 7

void print (char *imprimir)
{
    int i,j;
    for (i=0;i<HEIGHT;i++)
    {
        for (j=0;j<WIDTH;j++)
        {
            printf ("%2c",*(imprimir+(i*WIDTH)+j));
        }
        printf ("\n");
    }

}



int main ()
{
    //FILLING THE ARRAY
    char *array=malloc(WIDTH*HEIGHT);
    int i,j;
    for (i=0;i<HEIGHT;i++)
    {
        for (j=0;j<WIDTH;j++)
        {
            *(array+(i*WIDTH)+j)=(i*WIDTH)+j+'a';
        }
    }
    print (array);  
    //TRYING TO REVERSE IT
    char tmp;
    for (i=0;i<HEIGHT;i++)
    {
        for (j=0;j<WIDTH/2;j++)
        {
            tmp=*(array+(i*WIDTH)+j);
            *(array+(i*WIDTH)+j)=*(array+(i*WIDTH)+(WIDTH - 1 -j));
            *(array+(i*WIDTH)+(WIDTH - 1 -j))=tmp;
        }
    }
    printf ("PRINTING RESULT!\n");
    print (array);  

}
Run Code Online (Sandbox Code Playgroud)