#include <stdio.h> #include <stdlib.h> /* Puzzle D09 -- add two arrays */ #define COLS 6 #define ROWS 6 /* Generate a random integer min < = r < = max */ int randInt( int min, int max ) { return rand()%(max-min+1) + min ; } void print2DArray ( int nrows, int ncols, int x[nrows][ncols] ) { int r, c; for ( r=0; r<nrows; r++ ) { for ( c=0; c<ncols; c++ ) printf("%3d,", x[r][c] ); printf("\n"); } } void fill2Drandom( int nrows, int ncols, int x[nrows][ncols], int low, int high ) { int r, c; for ( r=0; r<nrows; r++ ) { for ( c=0; c<ncols; c++ ) x[r][c] = randInt( low, high ); } } void add2DArrays( int rows, int cols, int x[rows][cols] , int y[rows][cols], int sum[rows][cols] ) { int r, c; for ( r=0; r<rows; r++ ) for ( c=0; c<cols; c++ ) sum[r][c] = x[r][c]+y[r][c]; } int main() { int x[ROWS][COLS] ; int y[ROWS][COLS] ; int sum[ROWS][COLS] ; /* Fill the arrays with random integers */ fill2Drandom( ROWS, COLS, x, -10, +10 ); fill2Drandom( ROWS, COLS, y, -10, +10 ); /* Add the two arrays */ add2DArrays( ROWS, COLS, x, y, sum ); /* Print the arrays */ printf("Array x:\n"); print2DArray( ROWS, COLS, x ); printf("\n\nArray y:\n"); print2DArray( ROWS, COLS, y ); printf("\n\nSum:\n"); print2DArray( ROWS, COLS, sum ); /* Print the arrays, but with curious parameters */ printf("Array x:\n"); print2DArray( ROWS/2, COLS*2, x ); printf("\n\nArray y:\n"); print2DArray( ROWS/2, COLS*2, y ); printf("\n\nSum:\n"); print2DArray( ROWS/3, COLS*3, sum ); printf("\n"); return 0; }
It would be greatly informative to make some deliberate mistakes in the above program:
add2DArrays
with confused parameters.sum
array so it is different from the others.
Often, mistakes such as reversing the dimensions don't have an effect on the program.
In figuring out why, recall that a 2D array is stored as a linear sequence of
ints in main memory.
A 4x7 array takes up 28 ints in memory.
The same 28 ints could be regarded as a 7x4 array or a 14x2 array or a 2x14 matrix.
The parameters supplied to (say) print2DArray
could be any of the above.
Often programs deal with square arrays: arrays with the same number of rows and columns. You might test your program and find that it works perfectly with your sample arrays (all of which are square), only to discover when you release your code that it fails with non-square arrays.