2 lishidatang158 lishidatang158 于 2013.07.10 11:03 提问

以下两个C程序嵌套for循环中j=i是怎么遍历二维数组的?

#include
int main()
{
void change(int * p);
int a[5][5], * p, i, j;
printf("input matrix:\n");
for(i=0; i for(j=0; j scanf("%d",&a[i][j]);
p = &a[0][0];
change(p);
printf("Now,matrix:\n");
for(i=0; i {
for(j=0; j printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
void change(int * p)
{
int i, j, temp;
int * pmax, * pmin;
pmax = p;
pmin = p;
for(i=0; i for(j=i; j {
if(* pmax pmax = p + 5 * i + j;
if((* pmin> *(p+5*i+j)))
pmin = p + 5 * i + j;
}

temp = * (p+12);
*(p+12) = * pmax;

  • pmax = temp; temp = * p;
  • p = * pmin;
  • pmin = temp; pmin = p + 1; for(i=0; i * (p+5*i+j))) pmin = p + 5 * i + j; temp = * pmin;
  • pmin = * (p+4);
  • (p+4) = temp; pmin = p + 1; for(i=0; i * (p+5*i+j))) pmin = p + 5 * i + j; temp = * pmin;
  • pmin = * (p+20);
  • (p+20) = temp; pmin = p +1; for(i=0; i * (p+5*i+j))) pmin = p + 5 * i + j; temp = * pmin;
  • pmin = * (p+24);
  • (p+24) = temp; } 在change函数一开始的两个嵌套for循环中,为什么设j=i?是怎么遍历这个二维数组的?我自己设j=0,也能得到正确答案!

#include
int main()
{
void move(int * pointer);
int a[3][3], * p, i;
printf("input matrix:\n");
for(i=0; i<3; i++)
scanf("%d %d %d",&a[i][0],&a[i][1],&a[i][2]);
p = &a[0][0];
move(p);
printf("Now,matrix:\n");
for(i=0; i<3; i++)
printf("%d %d %d\n",a[i][0],a[i][1],a[i][2]);
return 0;
}
void move(int * pointer)
{
int i, j, t;
for(i=0; i<3; i++)
for(j=i; j<3; j++)
{
t = * (pointer+3*i+j);

  • (pointer+3*i+j) = * (pointer+3*j+i);
  • (pointer+3*j+i) = t; } } 在这个程序的move函数中,如果把嵌套的for循环中的j=i改为j=0,就得不到正确的答案了!
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!