-4
#include "stdio.h"

void main(){
 int a[2][2]={1, 2, 3, 4};
 int a[2][2]={1, 2, 3, 4};
 display(a, 2, 2);
 show(a, 2, 2);}
}

display(int *k, int r, int c){
int i, j, *z;
 for(i = 0; i < r; i++){
   z = k + i;
   printf("Display\n");
      for(j = 0; j < c; j++){
          printf("%d", *(z + j));
       }
  }
}

show(int *q, int ro, int co){
int i, j;
   for(i = 0; i < ro; i++){
     printf("\n");
     for(j = 0; j < co; j++){
       printf("%d", *(q + i*co + j));
     }
   }
}

Output:

Display
12
23
Show
12
34

Why Display() is not showing 1223 while show() gives 1234? Both uses the same logic to display the 2d array. Can any one help please?

4

2 回答 2

0

display您使用两个计数器,i用于行和j列。i由于数组在内存中是按顺序排列的,因此每次您想从一行移动到下一行时,您都需要增加一列的大小,即 c。因此,您应该添加i*c到 k,而不是i.

完整的功能:

display(int *k,int r,int c){
int i,j,*z;
 for(i=0;i<r;i++){
   z=k+i*c;
   printf("Display\n");
      for(j=0;j<c;j++){
          printf("%d",*(z+j));
       }
  }
}
于 2012-07-15T15:27:33.340 回答
0

使用指针访问二维数组:

#define R 2
#define C 2
...
int A[R][C]={1, 2, 3, 4};
for(i=0;i<R;i++)  
  for(j=0;j<C;j++)
    printf("%d ",*(*(A+i)+j));
...
于 2021-03-08T20:20:15.623 回答