我需要反转用指针表示法制作的2d数组。
要清楚,如果数组是
A B C D E
F G H I J
K L M N O
我需要:
E D C B A
J I H G F
O N M L K
到目前为止我的代码:
#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);
}
答案 0 :(得分:6)
你有两个错误。
;
,所以循环根本没有运行。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);
}
答案 1 :(得分:1)
至少是字符串for (j=0;j<WIDHT/2;j++);
中的错误,因为你不想在那里有一个空循环,对吗?
这是你的代码:
#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-1));
*(array+(i*WIDHT)+(WIDHT-j-1))=*tmp;
}
}
printf ("PRINTING RESULT!\n");
print (array);
}