//NAME: TwoDArrays.c
//
//PURPOSE:
//  To exercise using pointers with 2d arrays
//
#include <string.h>
#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[])
{

  //Indices
  int i,j,ii;

  //Dimensions of the Array
  long NAxis1=5;                      //Number of Rows
  long NAxis2=10;                     //Number of Columns

  //Declare a short int array
  short int ImS[NAxis1][NAxis2];      //Declare the array to hold the pixels
  long nCells = NAxis2*NAxis1;        //Total number of pixels

  //Fill the array first
  for (i=0; i<NAxis1; i++){
    for (j=0; j<NAxis2; j++){
      ImS[i][j] = i*NAxis2+j;
    }
  }

  //print the first row of numbers 
  short int (*ImP)[NAxis2];           //ImP is a pointer to an array of NAxis2 short ints
  short int *ImP2;                    //ImP2 is a pointer to a short int
  ImP  = ImS;                         //ImP now points to ImS[0], i.e. the first row
  ImP2 = ImS[0];                      //ImP2 now points to ImS[0][0], i.e. first element
 
  //Print this out
  printf("*ImP2 dereferences the pointer to ImS[0][0] and gives: %u \n", *ImP2);
  printf("*ImP dereferences the pointer to the first row ImS[0], which is another pointer: %u \n", *ImP);
  printf("ImP is the address of the first row: %u \n", ImP);
  printf("\n"); 
  printf("\n"); 

  for (ii=0; ii<nCells; ii++){
    printf("*(*ImP+ii) dereferences the pointer to ImS[0]+ii: %d \n", *(*ImP+ii));
    printf("*(ImP2+ii) dereferences the pointer to ImS[0]+ii: %d \n", *(ImP2+ii));
    printf("*ImP+ii yields an address of the ii_th element:   %u \n", *ImP+ii);
    printf("*(ImP+ii) yields the address of the ii_th row :   %u \n", *(ImP+ii));
  }
  printf("\n"); 
  return(0);
}

