Nguyễn Tấn Phát
PRO
last year
Nguyễncountry asked

How can we create a 3D array?

Abhilekh Gautam
Expert
last year

You can create a 3D array in C++ like this:

int arr[2][3][4] = {
    {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    },
    {
        {13, 14, 15, 16},
        {17, 18, 19, 20},
        {21, 22, 23, 24}
    }
};

Here, arr is a 3D array with dimensions 2 × 3 × 4:

  • It has 2 layers (or "pages")

  • Each layer contains 3 rows

  • Each row has 4 columns

Accessing Elements:

You can access or modify individual elements like this:

arr[1][2][3] = 99; // Sets the value in the second layer, third row, fourth column to 99

Use Case Tip:

3D arrays are useful for representing data like a stack of 2D grids—common in simulations, image processing, or games.

C++
This question was asked as part of the Learn C++ Basics course.