A two-dimensional array is a grid of rows and columns. To create one in the run-time stack, use something like
double grid[5][10];which creates an array of 5 rows and 20 columns in the run-time stack. To create it in the heap instead, use
double* grid = new double[5][10];To delete an array that is in the heap, use
delete [] grid;
To use a two-dimensional array, use grid[i][j] to indicate the variable in grid at row i, column j. Both rows and colums are numbered starting at 0.
You can also use grid[i] to indicate the entire row at index i. So
Storage of two-dimensional arrays
The variables of a two-dimensional array
are stored consecutively in memory by rows.
For example, if B is created by
int B[3][2];then the variables in array B are stored in the following order: B[0][0] B[0][1] B[1][0] B[1][1] B[2][0] B[2][1] In general, if array B has r rows and c columns then the memory address of B[i][j] is B + c*i + j. |
Passing two-dimensional arrays as parameters
Because the computation of the memory address
of B[i][j] requires knowledge of the number of
columns in two-dimensional array B, the compiler
needs to know how many columns B has.
If you pass a two-dimensional array as a parameter,
you must include the number of columns. For example,
// sum(A,n) returns the sum of all numbers in array // A[0,...,n-1]. int sum(int* A, int n) { int total = 0; for(int i = 0; i < n; i++) { total += A[i]; } return total; } // rowsums(B, r) returns an array of the row-sums of // two-dimensional array B, which has r rows. // For example, if B holds // 2 3 4 // 5 6 7 // 2 4 6 // 7 8 9 // then sum(B,4) returns an array (allocated in the heap // using new) holding // // 9 // 18 // 12 // 24 int* rowsums(int B[][3], int r) { int* A = new int[r]; for(int i = 0; i < r; i++) { A[i] = sum(B[i], 3); } return A; } |
Looping through a two-dimensional array
To look at each thing in a two-dimensional array,
you typically use two nested for-loops. For example,
the following function writes two-dimensional array
G in a grid format.
void show(int G[][5], int r) { for(int i = 0; i < r; i++) { for(int j = 0; j < 5; j++) { printf("%8i", G[i][j]); } printf("\n"); } }Note that the coding standards for this course require only one looop per function. To look at all members of a two-dimensional array with that restriction, you would write a function that handles a single row, as suggested by the following implementation of show. void showRow(int G[][5], int i) { for(int j = 0; j < 5; j++) { printf("%8i", G[i][j]); } printf("\n"); } void show(int G[][5], int r) { for(int i = 0; i < r; i++) { showRow(G, i); } } |
Write a statement that allocates a new two-dimensional array or doubles with 3 rows and 14 columns in the heap, and makes variable t point to it. Answer
Write a function that takes a two-dimensional array of ints as a parameter, where the array has 10 colums and 5 rows. The function should store 0 into each spot in the array. Answer