How do you have a function return a 2D array to be then accepted by another function?

Can someone show me the correct way to have a function return a 2D array, then have that same 2D array get pass through another function by its parameter?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

//Prototypes
char **giveArray();
void takeArray(int**);

int main(){
    char **prt = giveArray();
    takeArray(ptr);
return 0;}

char **giveArray()
{
      char 2DArray[2][2] = {{a,b} , {c,d}};

return 2DArray;}  


void takeArray(char2dArr[][2]){
     for(int i = 0; i < 2; i++){
          for(int j = 0; j < 2; j++)
              cout<<2dArr[i][j]<<endl;
          
     } 
}
Last edited on
1
2
3
4
5
char **giveArray()
{
      char 2DArray[2][2] = {{a,b} , {c,d}};

return 2DArray;} 

When this function returns, C++ automatically cleans up any local variables. As a result 2DArray now points to some unknown region in memory, so when reading/writing to the array, you will get undefined behaviour (i.e. program crashing). Also you forgot single quotation marks(' ') for the characters.

You could either:
Use a vector and return that.
If you have to use arrays, pass a 2D array as a parameter, and modify the elements that way.
Topic archived. No new replies allowed.