2 Dimensional Arrays
Implementing a database of information as a collection of
arrays can be inconvenient when we have to pass many
arrays to utility functions to process the
database.
It would be nice to have a single data structure
which can hold all the information, and pass it all at once.
2-dimensional arrays provide most of this capability.
Like a 1D array, a 2D array is a collection of data cells, all of
the same type, which can be given a single name. However, a 2D array
is organized as a matrix with a number of rows and columns.
How do we declare a 2D array?
Similar to the 1D array, we must specify the data type, the name, and
the size of the array. But the size of the array is described as
the number of rows and number of columns. For example:
int a[MAX_ROWS][MAX_COLS];
This declares a data structure that looks like:
How do we access data in a 2D array?
Like 1D arrays, we can access individual cells in a 2D array by using
subscripting expressions giving the indexes, only now we
have two indexes for a cell: its row index and its column index.
The expressions look like:
a[i][j] = 0;
or
x = a[row][col];
We can initialize all elements of an array to 0 like:
for(i = 0; i < MAX_ROWS; i++)
for(j = 0; j < MAX_COLS; j++)
a[i][j] = 0;
How do we pass a 2D array to a function?
Again, like 1D arrays, we simply pass the array by using its name, which is
a pointer to the entire block of data cells:
process(a);
But how do we declare a 2D array in the header of the function?
To understand this we have to look
to Overview.