Multi-Dimensional Arrays in C++


A multi-dimensional array is an array that contains other arrays. It's a fundamental data structure in C++ used to represent tables, matrices, and other structured data. In this guide, we'll explore multi-dimensional arrays in C++ and provide sample code to illustrate their usage.


Two-Dimensional Arrays

A two-dimensional array is a matrix-like structure with rows and columns. It is often used to represent grids of data. Here's an example:


#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
cout << "Two-Dimensional Array (Matrix):" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}

In this example, we declare a 3x3 two-dimensional array to represent a matrix and initialize it with values. We then use nested loops to iterate through the rows and columns and print the matrix.


Three-Dimensional Arrays

A three-dimensional array extends the concept to three dimensions and is often used for 3D data structures. Here's an example:


#include <iostream>
using namespace std;
int main() {
int cube[2][2][3] = {
{{1, 2, 3}, {4, 5, 6}},
{{7, 8, 9}, {10, 11, 12}}
};
cout << "Three-Dimensional Array (Cube):" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
cout << cube[i][j][k] << " ";
}
cout << " ";
}
cout << endl;
}
return 0;
}

In this example, we declare a 2x2x3 three-dimensional array to represent a cube and initialize it with values. We use nested loops to iterate through the three dimensions and print the cube.


Multi-Dimensional Arrays with Pointers

Multi-dimensional arrays can also be represented using pointers. Here's an example of a two-dimensional array with pointers:


#include <iostream>
using namespace std;
int main() {
int rows = 3;
int cols = 4;
int** matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
// Initialize the matrix
int value = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = value;
value++;
}
}
cout << "Two-Dimensional Array (Pointers):" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
// Deallocate memory
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
return 0;
}

In this example, we use dynamic memory allocation to create a two-dimensional array using pointers. We initialize and print the array and then deallocate the memory to avoid memory leaks.


Conclusion

Multi-dimensional arrays in C++ are versatile data structures that allow you to work with structured data in a grid or cube-like format. Whether you're representing a table of values or 3D structures, understanding multi-dimensional arrays is crucial for various applications in C++ programming.