/* plus2.c - Let's look at how + and * work with 2-d arrays in C. * The name of the array can be used like a pointer. */ #define NUM_ROWS 6 #define NUM_COLS 8 #include /* initialize - Put numbers in the array. * Unfortunately, C does not provide a way for us to look up the length * of an array, so let's put a sentinel value of 0 at the beginning of * its last row. I'm also going to put a 0 at the end of each row. * * Note that when a function takes a 2-d array as a parameter, we only need to * provide the number of columns. This is because in order to calculate * the address of each element in the array, we need the number of columns, * not the number of rows. */ void initialize(int a[][NUM_COLS]) { int i, j; for (i = 0; i < NUM_ROWS; ++i) { for (j = 0; j < NUM_COLS - 1; ++j) a[i][j] = 10 * (i + 1) + (j + 1); a[i][NUM_COLS - 1] = 0; // Put 0 at end of each row. } a[NUM_ROWS - 1][0] = 0; // Put 0 in bottom left corner also. } /* print_2d - Print a 2-dimensional array. We will continuously print * rows of the array up to and including the "last" row, which we define * to be the row that begins with zero. I'm creating this artificial * definition simply because I want to illustrate how + works with 2d arrays. */ void print_2d(int a[][NUM_COLS]) { int i, j; for (i = 0; ; ++i) { for (j = 0; j < NUM_COLS; ++j) printf("%5d", a[i][j]); printf("\n"); if (a[i][0] == 0) break; } } /* print_1d - Print a 1-dimensional array, up to and including the first * zero that we encounter. * * It is interesting to note that when a function takes a 1-d array as a * parameter, we do not indicate the size of the array. It is not necessary, * because the size of the array has no bearing on calculating the address * of each element of the array. */ void print_1d(int a[]) { int i; for (i = 0; ; ++i) { printf("%5d", a[i]); if (a[i] == 0) break; } } main() { int a[NUM_ROWS][NUM_COLS]; initialize(a); printf("Here is the entire array a:\n"); print_2d(a); printf("\nHere is the whole array starting at row 3:\n"); print_2d(a + 3); printf("\nHere is row 1:\n"); print_1d(a[1]); printf("\nHere is row 3:\n"); print_1d(*(a + 3)); printf("\nHere is row 4, starting at its element 2:\n"); print_1d(*(a + 4) + 2); // Here is an alternative way of writing a[i][j]: *(*(a+i)+j). printf("\na[3][2] equals %d\n", *(*(a + 3) + 2)); } /* Output: Here is the entire array a: 11 12 13 14 15 16 17 0 21 22 23 24 25 26 27 0 31 32 33 34 35 36 37 0 41 42 43 44 45 46 47 0 51 52 53 54 55 56 57 0 0 62 63 64 65 66 67 0 Here is the whole array starting at row 3: 41 42 43 44 45 46 47 0 51 52 53 54 55 56 57 0 0 62 63 64 65 66 67 0 Here is row 1: 21 22 23 24 25 26 27 0 Here is row 3: 41 42 43 44 45 46 47 0 Here is row 4, starting at its element 2: 53 54 55 56 57 0 a[3][2] equals 43 */