D07 Answer


Here is a complete program, including both the 1D and 2D versions of the summing function. Since a 2D array of integers is implemented as a 1D sequence of integers in main memory, the 1D function can be used to add them up. However, the compiler will complain unless you use a type cast to tell it that you know what you are doing.

/* Puzzle D07 -- Fool a 1D function into adding the integers in a 2D array */
#define NUMCOLS 15
#define NUMROWS 10


/* Generate a random integer  min <= r <= max */
int randInt( int min, int max )
{
  return (rand()*(max-min+1))/(RAND_MAX+1) + min ;
}

void print2DArray ( int x[][NUMCOLS], int nrows )
{
  int r, c;  /* row and column indexes for the array */

  /* Print elements in row major order */
  for ( r=0; r<nrows; r++ )
  {
    for ( c=0; c<NUMCOLS; c++ )
      printf("%3d ", x[r][c]  );
    printf("\n");
  }
}

void randomFill2DArray ( int x[][NUMCOLS], int nrows, int low, int high )
{
  int r, c;
  
  for ( r=0; r<nrows; r++ )
    for ( c=0; c<NUMCOLS; c++ )
      x[r][c] = randInt( low, high );
}

/*This is the 1D function that is "fooled" into adding a 2D array */
long addArray( int arr[], int size )
{
  int j;
  long sum = 0;

  for ( j=0; j<size; j++ )
    sum += arr[j] ;

  return sum;
}

long add2DArray( int x[][NUMCOLS], int nrows )
{
  int r, c;
  int sum = 0;

  for ( r=0; r<nrows; r++ )
    for ( c=0; c<NUMCOLS; c++ )
      sum += x[r][c] ;

  return sum;
}

int main(int argc, char *argv[])
{
  const int low = 0, high = 5;
  long sumA, sumB;

  int x[NUMROWS][NUMCOLS] ;

  /* Fill the array with random integers */
  srand( time(NULL) );
  randomFill2DArray( x, NUMROWS, low, high );

  /* Print the array using our function */
  print2DArray( x, NUMROWS );

  /* Fool the 1D function */
  sumA = addArray( (int*)x, NUMROWS*NUMCOLS );
  
  /* Check that answer is correct */
  sumB = add2DArray( x, NUMROWS );
  
  printf("\nThe sums are: %ld %ld\n", sumA, sumB);
  printf("\n");
  system("pause");
  return 0;
}

Comments: This puzzle is useful for practice in thinking about how memory is used and how arrays are implemented. But it is not a good example of how to write programs. If you are using a 2D array, probably you should write and use 2D functions with it.