【发布时间】:2016-04-27 15:28:07
【问题描述】:
这是我的代码示例(魔方):
int magicsqr(int *magic,int size);
int main()
{
int size,*ptr;
char stop;
repeat:
printf("Please Enter an Odd number for the magic square(3 or greater):\n");
scanf("%d",&size);
fflush(stdin);
ptr=(int*)calloc(size*size,sizeof(int));
while((size%2==0)||(size<=1))
{
printf("U entered a wrong number.\n");
repeat1:
printf("Do you wish to continue?(Y or N)\n");
scanf("%c",&stop);
fflush(stdin);
if(stop=='Y'||stop=='y')
goto repeat;
else if(stop=='N'||stop=='n')
printf("Thanks for trying our beta program.\n");
else
{
printf("U entered a wrong character.\n");
goto repeat1;
}
}
magicsqr(ptr,size);
return 0;
}
int magicsqr(int *magic,int size)
{
int i,j,num;
i=1;
j=(size+1)/2;
for(num=1;num<=size*size;num++)
{
*(magic+i*size+j)=num;
if(num%size==0){
i++;
continue;
}
if(i==1)
i=size;
else
i--;
if(j==size)
j=1;
else
j++;
}
for(i=1;i<=size;i++)
{
printf("\n");
for(j=1;j<=size;j++)
printf("%d\t",*(magic+i*size+j));
}
}
所以我有几个问题让我感到困惑..
1- 据我所知Arr[i][j]==*(Arr[i]+j)
那么为什么只有这个有效:*(magic+i*size+j).
2- 我在使用指针将二维数组传递给函数时阅读了很多内容,但不知何故我仍然很困惑,如何在这段代码中表示二维数组或更多。
3- 我还是个编程初学者,希望你能解释一下。
- 非常感谢大家,最后我使用指向指针和指针数组的指针来工作了。
【问题讨论】:
-
1.从代码中删除 I/O 代码,只留下重要部分。 2. 明确你的期望和实际得到的
-
我的代码运行良好并且打印结果正确,但我需要在我的代码中进行一些解释,我不知道它为什么会这样工作
-
您的代码中没有二维数组。而
fflush(stdin)是未定义的行为。 -
是的,它适用于我 b/c 我的编译器不接受 2 个输入