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 ⭐)

TEXT 📖 Display only
Type arrayName[Rows][Cols];

Output:

TEXT 📖 Display only
(Program output)

Example:

CPP
int matrix[3][4]; // 3 rows, 4 columns 2D array

Memory layout:

TEXT 📖 Display only
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

CPP
#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

CPP
#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

CPP
#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

CPP
#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

CPP
#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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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

CPP
#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:

CPP
#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:

CPP
#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:


▶ Example 3: Traversing a 2D array to calculate the sum (Difficulty ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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:

  1. Use std::vector<std::vector<int>>>` (recommended, we'll learn this later)
  2. Use dynamic memory allocation (we'll learn pointers and new later)

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


📝 Exercises

  1. Basic (Difficulty ⭐): Declare a 2×3 2D array, initialized as:
TEXT 📖 Display only
1 2 3
4 5 6

Then output the array.

  1. 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).
TEXT 📖 Display only
Original matrix:
1 2 3
4 5 6
7 8 9

Transposed:
1 4 7
2 5 8
3 6 9
  1. Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "Tic-Tac-Toe" game:
  2. Use a 3×3 2D array to represent the board
  3. Two players take turns (one uses X, the other uses O)
  4. Check if a player has formed a line (horizontal, vertical, or diagonal)

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.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏