C++: Multi-Dimensional Arrays
Last updated: 2026-08-26
If a one-dimensional array is like "a row of mailboxes", what about representing tabular data (like Excel spreadsheets, chessboards, matrices)?
That's where multi-dimensional arrays come in — arrays of arrays.
1. Two-Dimensional Arrays
(1) 1.1 What Is a Two-Dimensional Array?
A two-dimensional array is an "array of arrays" — each element is itself an array.
| Real-Life Analogy | Program Equivalent |
|---|---|
| Excel spreadsheet (rows × columns) | 2D array |
| Chessboard (8 × 8) | 2D array |
| Matrix (3 × 3) | 2D array |
(2) 1.2 Declaring a Two-Dimensional Array
Syntax:
▶ Example 2: Code example (Difficulty ⭐)
Type arrayName[Rows][Cols];
Output:
(Program output)
Example:
int matrix[3][4]; // 3 rows, 4 columns 2D array
Memory layout:
matrix[0][0] matrix[0][1] matrix[0][2] matrix[0][3] ← Row 0
matrix[1][0] matrix[1][1] matrix[1][2] matrix[1][3] ← Row 1
matrix[2][0] matrix[2][1] matrix[2][2] matrix[2][3] ← Row 2
💡 Key point: In a 2D array, the first index is the row, the second index is the column.
2. Initializing a Two-Dimensional Array
(1) 2.1 Initialization at Declaration
#include <iostream>
int main() {
// Method 1: Initialize by row
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Method 2: Initialize sequentially (not recommended, poor readability)
int matrix2[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
return 0;
}
(2) 2.2 Partial Initialization
#include <iostream>
int main() {
int matrix[3][4] = {
{1, 2}, // First row: only first two initialized, rest become 0
{5}, // Second row: only first initialized, rest become 0
{} // Third row: all become 0
};
return 0;
}
💡 Tip: Omitted rows or columns are automatically initialized to 0.
3. Accessing 2D Array Elements
(1) 3.1 Reading Elements
#include <iostream>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
std::cout << "Row 1, Col 1: " << matrix[0][0] << std::endl; // 1
std::cout << "Row 2, Col 3: " << matrix[1][2] << std::endl; // 7
std::cout << "Row 3, Col 4: " << matrix[2][3] << std::endl; // 12
return 0;
}
(2) 3.2 Modifying Elements
#include <iostream>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
matrix[1][2] = 100; // Change row 2, column 3 to 100
std::cout << "Modified element: " << matrix[1][2] << std::endl; // 100
return 0;
}
4. Traversing a 2D Array
(1) 4.1 Using Nested for Loops
#include <iostream>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Outer loop: iterate over rows
for (int i = 0; i < 3; i++) {
// Inner loop: iterate over columns
for (int j = 0; j < 4; j++) {
std::cout << matrix[i][j] << "\t";
}
std::cout << std::endl; // Newline
}
return 0;
}
💡 Key point: The outer loop controls rows, the inner loop controls columns.
5. Practice: Matrix Addition
▶ Example 1: Adding two 3×3 matrices (Difficulty ⭐⭐)
#include <iostream>
int main() {
int A[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int B[3][3] = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int C[3][3]; // Result matrix
// Matrix addition
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// Output result
std::cout << "Matrix C = A + B: " << std::endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cout << C[i][j] << "\t";
}
std::cout << std::endl;
}
return 0;
}
Output:
Matrix C = A + B:
10 10 10
10 10 10
10 10 10
6. Three-Dimensional Arrays (Optional)
(1) 6.1 What Is a Three-Dimensional Array?
A three-dimensional array is an "array of 2D arrays".
| Real-Life Analogy | Program Equivalent |
|---|---|
| Multiple 2D tables stacked together | 3D array |
| Cube (length × width × height) | 3D array |
(2) 6.2 Declaration and Access
#include <iostream>
int main() {
int cube[2][3][4]; // 2 layers, 3 rows, 4 columns
// Initialize
cube[0][1][2] = 5; // Layer 0, row 1, column 2
cube[1][2][3] = 10; // Layer 1, row 2, column 3
return 0;
}
💡 Tip: 3D arrays are hard to visualize and are typically only used in scientific computing and graphics. In real projects, prefer std::vector (which we'll learn later).
7. Common Mistakes
(1) 7.1 Swapping Index Order
Error example:
#include <iostream>
int main() {
int matrix[3][4];
matrix[1][2] = 5; // ✅ Correct: row 1, column 2
matrix[2][1] = 10; // ✅ Correct: row 2, column 1
// ❌ Mistake: swapped row and column
// Wanted to access row 1, column 2, but accessed row 2, column 1
std::cout << matrix[2][1] << std::endl;
return 0;
}
(2) 7.2 Array Out of Bounds
Error example:
#include <iostream>
int main() {
int matrix[3][4];
matrix[3][0] = 5; // ❌ Out of bounds! Max row index is 2
matrix[0][4] = 10; // ❌ Out of bounds! Max column index is 3
return 0;
}
💡 Tip: For a 2D array matrix[m][n], the index ranges are:
- Rows:
0tom-1 - Columns:
0ton-1
▶ Example 3: Traversing a 2D array to calculate the sum (Difficulty ⭐)
#include <iostream>
int main() {
int scores[3][4] = {
{85, 90, 78, 92},
{88, 76, 95, 80},
{70, 85, 88, 90}
};
int total = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
total += scores[i][j];
}
}
std::cout << "Total: " << total << std::endl;
std::cout << "Average: " << total / 12 << std::endl;
return 0;
}
Output:
Total: 967
Average: 80
❓ FAQ
Q: How are 2D arrays stored in memory? A: C++ 2D arrays use row-major order — all elements of the first row are stored first, then the second row, and so on. > > matrix[3][4] memory layout: > [0][0] [0][1] [0][2] [0][3] [1][0] [1][1] ... [2][3] > Q: How do I pass a 2D array to a function? A: You need to pass the array name, row count, and column count. > > void printMatrix(int arr[4], int rows) { // Column count must be specified! > for (int i = 0; i < rows; i++) { > for (int j = 0; j < 4; j++) { > std::cout << arr[i][j] << "\t"; > } > std::cout << std::endl; > } > } > Q: Can 2D arrays have dynamic sizes? A: Not with regular arrays (size must be determined at compile time).
Solutions:
- Use
std::vector<std::vector<int>>>` (recommended, we'll learn this later)- Use dynamic memory allocation (we'll learn pointers and
newlater)
Q: What's the most important thing about multi-dimensional arrays? A: Understand the core concepts first, then reinforce them through practice examples.
Q: How can I efficiently practice multi-dimensional arrays? A: Start with simple examples, gradually increase difficulty, and always test your code.
📖 Summary
- 2D arrays are "arrays of arrays", suitable for representing tabular data
- Declaration:
Type arrayName[Rows][Cols]; - Access:
arrayName[RowIndex][ColIndex] - Traversal: Use nested for loops (outer loop for rows, inner loop for columns)
- C++ 2D arrays are stored in row-major order
- When passing a 2D array as a parameter, the column count must be specified
📝 Exercises
- Basic (Difficulty ⭐): Declare a 2×3 2D array, initialized as:
1 2 3
4 5 6
Then output the array.
- Intermediate (Difficulty ⭐⭐):
Write a function
void transpose(int arr[3], int rows)that computes the transpose of a 3×3 matrix (swap rows and columns).
Original matrix:
1 2 3
4 5 6
7 8 9
Transposed:
1 4 7
2 5 8
3 6 9
- Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "Tic-Tac-Toe" game:
- Use a 3×3 2D array to represent the board
- Two players take turns (one uses
X, the other usesO) - Check if a player has formed a line (horizontal, vertical, or diagonal)
- 2D arrays: row-major storage, declaration format: Type arrayName[Row][Col]
- Nested for loops traverse 2D arrays
- Common use cases for multi-dimensional arrays: matrices, tables, images
- Column count must be specified when passing a 2D array as a function parameter
- Jagged 2D arrays can be implemented using pointer arrays
8. 🚀 Next Steps
Now that you've learned multi-dimensional arrays, next we'll study C-style strings (lesson 18) — representing strings with character arrays and understanding the underlying principles of C++ strings.