Table of contents
1.
Introduction
2.
Initialization Using Initializer List
3.
Runtime Initialization Using Loops
4.
Ways to declare 3D array
5.
Inserting values in 3D array
6.
Converting 3D array into 2D array
7.
Converting 2D array into 3D array
8.
Frequently Asked Questions
8.1.
What is the maximum size of a 3D array in C?
8.2.
Can we have different sizes for each dimension in a 3D array?
8.3.
How do we access elements in a 3D array using pointers?
9.
Conclusion
Last Updated: Dec 6, 2024
Easy

3 Dimensional Array in C

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

3D arrays in C are a way to store data in three dimensions - like a cube or a box. They allow you to organize information in a more structured way than 1D or 2D arrays. 3D arrays can be useful for representing things like 3D coordinates, RGB color values, or data points in 3D space. 

3 Dimensional Array in C

In this article, we'll discuss the basics of working with 3D arrays in C, like how to declare them, initialize their values, access and update elements, convert between 2D and 3D arrays, and dynamically allocate memory for them. 

Initialization Using Initializer List

One way to initialize a 3D array is using an initializer list when you declare it. This allows you to set all the initial values at once. For example:

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}}
};


In this code, we declare a 3D integer array called `arr` with dimensions 2x3x4 (2 layers, 3 rows, 4 columns). The initializer list is enclosed in curly braces {} and specifies all the values for the array. 

The outer curly braces represent the layers, the middle ones represent rows within each layer, and the inner ones are the individual elements in each row. So `{1, 2, 3, 4}` is the first row of the first layer, `{5, 6, 7, 8}` is the second row of the first layer, and so on.

The initializer list is convenient to use if you know all the array values ahead of time. It helps you to visualize the 3D structure. However, for very large arrays, it can be cumbersome to list out every single value.

Zero Initialization: If you declare a 3D array without specifying any initial values, all its elements will be automatically initialized to zero. This is called zero initialization. Let’s see how you can declare a zero-initialized 3D array:

int arr[2][3][4] = {0};

 

By setting the first element to 0 and leaving out the rest of the initializer list, all elements will default to 0. This works because the compiler fills in the missing values with zeros.

You can also leave out the initializer entirely:

int arr[2][3][4];


In this case, the elements will still be zero-initialized (for global or static arrays). However, for local arrays, the values will be undefined until explicitly set.

Zero initialization is useful when you want to start with a "clean slate" and assign values later in your program. It ensures that there's no garbage data in the array.

Runtime Initialization Using Loops

Instead of using an initializer list, you can also initialize a 3D array at runtime using loops. This is useful when the values need to be computed or depend on user input. 

For example: 

int arr[2][3][4];
// Initialize using nested loops
for(int i = 0; i < 2; i++) {
   for(int j = 0; j < 3; j++) {
      for(int k = 0; k < 4; k++) {
         arr[i][j][k] = i + j + k;
      }
   }
}


In this code, we declare the 3D array `arr` without specifying any initial values. Then, we use three nested loops to iterate over each element and assign a value based on the indices `i`, `j`, and `k`. 

The outer loop iterates over the layers (0 to 1), the middle loop iterates over the rows within each layer (0 to 2), and the inner loop iterates over the elements in each row (0 to 3). The value assigned to each element is the sum of its indices.

Note: If you use loops to initialize the array, you will have more flexibility, as you can use complex expressions, conditionals, or even call functions to determine the values. It's particularly handy when the values have a pattern or formula based on their positions.

Ways to declare 3D array

There are a few different ways to declare a 3D array in C. Let’s look at the most common ones:

1. With constant size:

   int arr[2][3][4];


This declares a 3D integer array with 2 layers, 3 rows, and 4 columns. The size of each dimension is fixed and must be a constant known at compile-time.


2. With variable size:

   int n = 2, m = 3, p = 4;
   int arr[n][m][p];


This declares a 3D integer array with dimensions specified by variables `n`, `m`, and `p`. The sizes can be determined at runtime, but once declared, the array size is fixed.


3. With dynamic allocation:

   int ***arr;
   arr = (int ***)malloc(2 * sizeof(int **));
   for(int i = 0; i < 2; i++) {
      arr[i] = (int **)malloc(3 * sizeof(int *));
      for(int j = 0; j < 3; j++) {
         arr[i][j] = (int *)malloc(4 * sizeof(int));
      }
   }


This dynamically allocates memory for a 3D integer array using `malloc`. The size of each dimension is specified at runtime. This allows for more flexibility but requires manual memory management.

Note: The choice of declaration depends on your specific needs - whether the array size is fixed or variable, which is known at compile-time or runtime, and if you need the flexibility of dynamic allocation.

Inserting values in 3D array

Once you have declared a 3D array, you can insert values into it using the array indices. For example: 

int arr[2][3][4];
// Inserting values
arr[0][0][0] = 1;
arr[0][0][1] = 2;
arr[0][0][2] = 3;
arr[0][0][3] = 4;
arr[0][1][0] = 5;
arr[0][1][1] = 6;
// ... and so on

 

In this code, we have a 3D integer array `arr` with dimensions 2x3x4. To insert values, you specify the indices for each dimension separated by square brackets [].

For example, `arr[0][0][0] = 1` assigns the value 1 to the element at the first layer (index 0), first row (index 0), and first column (index 0). Similarly, `arr[0][1][1] = 6` assigns the value 6 to the element at the first layer, second row, and second column.

You can also use loops to insert values more concisely:

for(int i = 0; i < 2; i++) {
   for(int j = 0; j < 3; j++) {
      for(int k = 0; k < 4; k++) {
         arr[i][j][k] = some_value;
      }
   }
}

 

This nested loop structure allows you to iterate over each element and assign values based on the loop variables `i`, `j`, and `k`.

Converting 3D array into 2D array

Sometimes, you might need to convert a 3D array into a 2D array. This can be useful if you want to process the data in a flattened format or pass it to a function that expects a 2D array. 

Let’s take an example of how to convert a 3D array to a 2D array:

int arr3D[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}}
};

int rows = 2 * 3;
int cols = 4;
int arr2D[rows][cols];

// Converting 3D to 2D
int index = 0;
for(int i = 0; i < 2; i++) {
   for(int j = 0; j < 3; j++) {
      for(int k = 0; k < 4; k++) {
         arr2D[index][k] = arr3D[i][j][k];
      }
      index++;
   }
}

 

In this code, we have a 3D integer array `arr3D` with dimensions 2x3x4. We want to convert it into a 2D array `arr2D` with dimensions 6x4 (2*3 rows and 4 columns).

To convert the array, we use nested loops to iterate over the elements of `arr3D`. The outer loop iterates over the layers, the middle loop iterates over the rows within each layer, and the inner loop iterates over the elements in each row.

Inside the loops, we copy the elements from `arr3D` to `arr2D`. We use a variable `index` to keep track of the current row in `arr2D`. For each layer and row in `arr3D`, we copy the elements to the corresponding row in `arr2D`.

After the loops complete, `arr2D` will contain the flattened version of `arr3D`, with each layer and row of `arr3D` becoming a separate row in `arr2D`.

Converting 2D array into 3D array

Converting a 2D array into a 3D array is the reverse process of converting a 3D array to a 2D array. You need to specify the dimensions of the 3D array and map the elements from the 2D array to the corresponding positions in the 3D array. For example:

int arr2D[6][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}
};

int layers = 2;
int rows = 3; 
int cols = 4;
int arr3D[layers][rows][cols];

// Converting 2D to 3D
int index = 0;
for(int i = 0; i < layers; i++) {
  for(int j = 0; j < rows; j++) {
    for(int k = 0; k < cols; k++) {
      arr3D[i][j][k] = arr2D[index][k];
    }
    index++;
  }
}


In this code, we have a 2D integer array `arr2D` with dimensions 6x4. We want to convert it into a 3D array `arr3D` with dimensions 2x3x4.

To convert the array, we use nested loops similar to the previous example. The outer loop iterates over the layers of `arr3D`, the middle loop iterates over the rows within each layer, and the inner loop iterates over the elements in each row.

Inside the loops, we copy the elements from `arr2D` to `arr3D`. We use the variable `index` to keep track of the current row in `arr2D`. For each layer and row in `arr3D`, we copy the corresponding elements from `arr2D`.

After the loops complete, `arr3D` will contain the reshaped version of `arr2D`, with the elements distributed across the specified layers, rows, and columns.

Frequently Asked Questions

What is the maximum size of a 3D array in C?

The maximum size of a 3D array depends on the available memory. The total number of elements should not exceed the maximum value of the `int` data type.

Can we have different sizes for each dimension in a 3D array?

Yes, it's possible to have different sizes for each dimension in a 3D array. For example, you can declare an array as `int arr[2][3][4]`, where the dimensions are 2, 3, and 4.

How do we access elements in a 3D array using pointers?

To access elements in a 3D array using pointers, you can use the following syntax: `*(*(*(arr + i) + j) + k)`, where `arr` is the array name and `i`, `j`, `k` are the indices for each dimension.

Conclusion

In this article, we discussed the concept of 3D arrays in C. We learned how to declare 3D arrays, initialize them using initializer lists, zero initialization, and runtime initialization with loops, and cover different ways to insert and update values in a 3D array. Moreover, we discussed converting between 3D and 2D arrays and dynamically allocating memory for 3D arrays using `malloc`. 

You can also check out our other blogs on Code360.

Live masterclass