-1

I don't know what's wrong happening while i trying to return 2-d array from function and tend to use it further. I'am doing this in code blocks(using c++)

The error is: cannot convert 'int (*)[3]' to 'int**

HERE IS THE CODE:

 int** returnArray(){

 int a[3][3]={{1,2,5},{8,1,2}};
 return a;

 }

int main()

{
 int** k=returnArray();
 return 0;



 }
Community
  • 1
  • 1

1 Answers1

0

When you return an address of a local variable from a function, that address becomes invalid because the variable ceases to exists when the function returns. Plain arrays in C++ (and C) don't get passed by value, unless wrapped in a structure.

You can return a copy of your array and hope that the compiler eliminates the unnecessary copy (they usually do).

E.g.:

#include <iostream>

struct MyArray {
    int a[3][3];
};

MyArray returnArray(){
    MyArray a = {{{1,2,5},{8,1,2}}};
    return a;
}

int main() {
    MyArray a_copy = returnArray();
    std::cout << a_copy.a[0][0] << ' ' << a_copy.a[0][1]  << ' ' << a_copy.a[0][2] << '\n';
    std::cout << a_copy.a[1][0] << ' ' << a_copy.a[1][1]  << ' ' << a_copy.a[1][2] << '\n';
    std::cout << a_copy.a[2][0] << ' ' << a_copy.a[2][1]  << ' ' << a_copy.a[2][2] << '\n';
}
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271