VOOZH about

URL: https://www.geeksforgeeks.org/dsa/how-to-pass-and-return-a-3-dimensional-array-in-c/

⇱ How to pass and return a 3-Dimensional Array in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to pass and return a 3-Dimensional Array in C++?

Last Updated : 21 Jun, 2022

In C++ a 3-dimensional array can be implemented in two ways:

  • Using array (static)
  • Using vector (dynamic)

Passing a static 3D array in a function: Using pointers while passing the array. Converting it to the equivalent pointer type.

char ch[2][2][2];
void display(char (*ch)[2][2]) {
    . . .
}

Program to pass a static 3D array as a parameter:


Output
ch[0][0][0] = a
ch[0][0][1] = b
ch[0][1][0] = c
ch[0][1][1] = d
ch[1][0][0] = e
ch[1][0][1] = f
ch[1][1][0] = g
ch[1][1][1] = h

Time Complexity:   O(n3)

Auxiliary Space: O(1)

Passing 3D vector (dynamic array): When a vector is passed to a function, it can either be passed by value, where a copy of the vector is stored, or by reference, where the address of the vector is passed.

  • Pass by value: 

void function(vector <vector <vector < char >>> ch) {
    . . .
}

  • Pass by reference (Better):

void function(vector< vector < vector < char>>> &ch) {
    . . .
}

Program to pass a dynamic 3D array as a parameter:


Output
ch[0][0][0] = a
ch[0][0][1] = b
ch[0][1][0] = c
ch[0][1][1] = d
ch[1][0][0] = e
ch[1][0][1] = f
ch[1][1][0] = g
ch[1][1][1] = h

Time Complexity:  O(n3)

Auxiliary Space: O(1)

A static array cannot be returned from a function in C++. So we have to pass a 3D vector from a function to get the functionality of returning a 3D array.

vector <vector< vector <char>>> fun() {
    vector <vector< vector <char>>> ch;
    . . .
    return ch;
}

Comment