Jatin
Jatin

Reputation: 14269

returning a 2D array in c++ using typecasting

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?

Upvotes: 0

Views: 186

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545558

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:

matrix_2d function() {
    matrix_2d M = {{1, 2}, {3, 4}};
    return M;
}

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(): inside function you 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.

Upvotes: 3

RonaldBarzell
RonaldBarzell

Reputation: 3830

To return a 2D array, make sure you dynamically allocate it, then return the pointer. The problem with your code is that you are returning a pointer to a local variable, which will cause problems.

Basically, you'll want to do something like this (skeleton):

int** function()
{
    int** M;
    // Allocate M here
    return M;
}

Upvotes: 2

Related Questions