Selasa, 02 Oktober 2012

Using pointer to initialize Array 2D ( Menggunakan Pointer untuk menginisialisasi Array 2D)

Ok, in this post, I would like to share about pointer in c. Even this pointer an old stuff, but, if you are interest in kernel and embedded system, it always use. Go to the topics, I'll share a little c code to initialize a 2D array with a pointer. The pointer will be a parameter in a function. This is the code:

#include <stdio.h>

void main(){
 int a[2][2];
 int b[2][2];
 int i,j;
 initArray(a,2,2);
 //display(a,2,2);
 //show(b,2,2);
 //show(a,2,2);
 for(i=0;i<2;i++) {
     for(j=0;j<2;j++) {
         printf("a[%d][%d]: %d ",i,j,a[i][j]);
     }
     printf("\n");
 }
}

void initArray(int *k, int r, int c) {
    int i,j,*z;
    for(i=0;i<r;i++) {
        z = k+i*r;
        for(j=0;j<c;j++) {
            printf("arr[%d][%d]: ",i,j);
            scanf("%d", &(*(z+j)));
        }
    }
}
display(int *k,int r,int c){
int i,j,*z;
printf("Display\n");
 for(i=0;i<r;i++){
   z=k+i*r;
   printf("%p \n",z);
      for(j=0;j<c;j++){
          printf("%d, %p\n",*(z+j), &(*(z+j)));
       }
  }
}

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

And this is the capture of the running program.






Go Open Source... and Happy Coding.

Tidak ada komentar: