โ Representation of Two-Dimensional Arrays in Memory (Detailed BCA Exam Answer)
โ 1. Introduction
A Two-Dimensional Array (2D Array) stores elements in the form of rows and columns, like a matrix.
โ Example:
int A[3][4];
It has:
- 3 rows
- 4 columns
- Total elements = 3 ร 4 = 12
๐ Although it looks like a table, memory in computer is linear (1D), so a 2D array is stored in memory in a continuous sequence.
โ 2. Methods of Memory Representation of 2D Arrays
There are two common methods to store 2D arrays in memory:
โ
1. Row-Major Order (used in C/C++)
โ
2. Column-Major Order (used in FORTRAN / MATLAB)
โ 3. Row-Major Order Representation
โ Meaning
In Row-Major Order, elements are stored row by row.
๐ First, all elements of Row 0, then Row 1, then Row 2, and so on.
โ Example
Let:
int A[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
๐ Table form:
A[0][0] A[0][1] A[0][2]
A[1][0] A[1][1] A[1][2]
A[2][0] A[2][1] A[2][2]
โ Stored in memory (Row-Major):
1, 2, 3, 4, 5, 6, 7, 8, 9
โ Address Calculation Formula (Row-Major)
[
LOC(A[i][j]) = Base(A) + [(i \times N) + j] \times W
]
Where:
- LOC(A[i][j]) = address of element
A[i][j] - Base(A) = address of first element
A[0][0] - i = row index
- j = column index
- N = number of columns
- W = size of each element (bytes)
โ Example Calculation
Assume:
- Base(A) = 1000
- W = 4 bytes
- N = 3 columns
Find address ofA[2][1]
[
LOC(A[2][1]) = 1000 + [(2 \times 3) + 1] \times 4
]
[
= 1000 + (6+1)\times 4
= 1000 + 28
= 1028
]
โ
Address of A[2][1] = 1028
โ 4. Column-Major Order Representation
โ Meaning
In Column-Major Order, elements are stored column by column.
๐ First all elements of Column 0, then Column 1, then Column 2, etc.
โ Example (Same Array)
Matrix:
1 2 3
4 5 6
7 8 9
โ Stored in memory (Column-Major):
1, 4, 7, 2, 5, 8, 3, 6, 9
โ Address Calculation Formula (Column-Major)
[
LOC(A[i][j]) = Base(A) + [(j \times M) + i] \times W
]
Where:
- M = number of rows
โ Example Calculation
Assume:
- Base(A) = 1000
- W = 4 bytes
- M = 3 rows
Find address ofA[2][1]
[
LOC(A[2][1]) = 1000 + [(1 \times 3) + 2] \times 4
]
[
= 1000 + (3+2)\times 4
= 1000 + 20
= 1020
]
โ
Address of A[2][1] = 1020
โ 5. Difference Between Row-Major and Column-Major
| Feature | Row-Major Order | Column-Major Order |
|---|---|---|
| Storage Order | Row wise | Column wise |
| Used In | C, C++ | FORTRAN, MATLAB |
| Formula Uses | Columns (N) | Rows (M) |
| First Stored | First row | First column |
โ 6. Conclusion
A two-dimensional array is stored in contiguous memory, but because memory is linear, it is stored using either:
โ
Row-Major Order (row by row โ C/C++)
โ
Column-Major Order (column by column โ FORTRAN)
Address of any element can be calculated using standard formulas.
