int** function()
{
int M[2][2] = {{1,2},{3,4}};
return (int **)M; //is this valid?
}
void anotherFn()
{
int **p = new int*[2];
for(int i = 0; i<2; i++) {
p[i] = new int[2];
}
p = function();
cout << p[0][0];
}
The above code compiled but gave runtime error. So, can I return a 2D array only if it was declared as double pointer or is there some way I can return an array as a 2D pointer?
You are representing a 2D array as a pointer to pointer to int. That is a bad idea. A better idea is to use a
std::vector<std::vector<int>>. Better yet would be to use a dedicated class. But the point is that once you get rid of pointers you can return the value without any problem:This works quite well for an appropriate definition of
matrix_2d(see above).Your code makes this whole process much more complicated by using pointers, and accesses invalid memory. In particular, you are allocating memory in your main function, but then you are discarding the pointer to that memory by reassigning it with the result of
function(): insidefunctionyou aren’t using the previously-allocated memory, you are using stack-allocated memory and returning a pointer to that. Once the function exits, that stack-allocated memory is gone.