PROJECTENGRAM

TWO-DIMENSIONAL ARRAYS (2D ARRAYS)

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:

『』
C
dataType arrayName[rows][columns];

Examples:

『』
C
int matrix[3][4];
char ticTacToe[3][3];

Initialization

Syntax:

『』
C
int table[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

Partial initialization:

『』
C
int data[3][2] = {
    {10, 20},
    {30}
};

Without inner braces:

『』
C
int values[2][2] = {11, 22, 33, 44};

Accessing Elements

Syntax:

『』
C
arrayName[row][column]

Example:

『』
C
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:

『』
C
#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 via arr[row][col]. Traverse with nested loops. When passing to functions, always specify the column dimension.

Related: Source / Reference:

◇References & Navigation

CONFIRMATION // 理解度の確認

ACTIVE RECALL VERIFICATION

Select an answer to verify conceptual comprehension and reveal the technical rationale.

Q1

How is a two-dimensional array typically conceptualized?

Q2

In the declaration int matrix[4][5];, how many total elements can the array hold?

Q3

What is the correct way to initialize a 2D array?