Two-Dimensional Arrays (2D Arrays)
Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Data Structures #◇Data Types #◇Structured Programming #◇Memory Management
◇Overview
A 2D array is a table (matrix) consisting of rows and columns.
◇Details / Theory
Definition
A 2D array is a table (matrix) consisting of rows and columns.
Declaration
Syntax:
dataType arrayName[rows][columns];
Examples:
int matrix[3][4];
char ticTacToe[3][3];
Initialization
Syntax:
int table[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Partial initialization:
int data[3][2] = {
{10, 20},
{30}
};
Without inner braces:
int values[2][2] = {11, 22, 33, 44};
Accessing Elements
Syntax:
arrayName[row][column]
Example:
int val = mat[1][2]; // Accesses value 6
Memory Layout (Row-Major Order)
In C, 2D arrays are stored row by row.
Personal Note: Row-major order affects performance and interoperability.
Traversing 2D Arrays
Example:
#define ROWS 2
#define COLS 3
int myMatrix[ROWS][COLS] = {{1,2,3}, {7,8,9}};
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
printf("myMatrix[%d][%d] = %d\n", r, c, myMatrix[r][c]);
}
}
◇Common Pitfalls
Confusing row-major order — in C, arr[i][j] stores row i contiguously, so arr[0][0], arr[0][1], ..., arr[0][COLS-1], arr[1][0], ... Forgetting inner braces during initialization — int arr[2][3] = {{1,2,3},{4,5,6}} is clearer and less error-prone than a flat list Swapping row and column indices — arr[row][col], not arr[col][row] Using a single loop to traverse a 2D array — always use nested loops (outer for rows, inner for columns) Passing to functions without specifying the column dimension — void f(int arr[][COLS], int rows) is required
◇Summary
TL;DR — 2D arrays are declared as
type name[ROWS][COLS], stored in row-major order. Initialize with nested braces. Access viaarr[row][col]. Traverse with nested loops. When passing to functions, always specify the column dimension.
◇Links
Related: Source / Reference:
◇References & Navigation
- Previous Topic: ◇One-Dimensional Arrays (1D Arrays)
- Next Topic: ◇Multidimensional Arrays (3D+)
- Related Notes: ◇Dimensions of Arrays, ◇Multidimensional Arrays (3D+)
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
How is a two-dimensional array typically conceptualized?
In the declaration int matrix[4][5];, how many total elements can the array hold?
What is the correct way to initialize a 2D array?