Skip to content
Home ยป Representation of Two Dimensional Arrays in Memory

Representation of Two Dimensional Arrays in Memory

โœ… 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 of A[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 of A[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

FeatureRow-Major OrderColumn-Major Order
Storage OrderRow wiseColumn wise
Used InC, C++FORTRAN, MATLAB
Formula UsesColumns (N)Rows (M)
First StoredFirst rowFirst 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.