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.
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];
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;
1D arrays can be represented as a vector of variables and 2D arrays can be represented like a matrix of variables. This is illustrated below.
A
gain, 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?
The prototype would look something like this:
int process(int x[][col-size]);
To understand this we have to know how the 2D array is stored in memory.