Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory in a function and returning it

Tags:

int** transpose(int** matrix,int row, int column)
{
    int** new_mat = new int*[column];


    for(int i = 0; i < column; i++)
    {
        new_mat[i] = new int[row];
    }
    for(int i  = 0; i < row; i++ )
    {
        for(int j = 0; j < column; j ++)
        {
            new_mat[j][i] = matrix[i][j];
        }
    }

    return new_mat;
}

I have written this function but something feels wrong I couldn't decide whether should I delete new_mat somehow basically function returns this value how should I manage with memory without using any smart pointers or something?

like image 885
Cagri Alp Avatar asked Dec 05 '18 08:12

Cagri Alp


1 Answers

The caller would use the returned matrix.

Moreover, it could acquire ownership. As a result, when the matrix would be no longer needed, it could delete it.

Another option, is for you, to provide another function, that will delete the matrix. The caller then, must call that function to de-allocate the dynamically allocated memory.


However, smart pointers is a nice C++ feature, and I encourage you to give them a shot.

Furthermore, since this C++, you could use a std::vector<std::vector<int>> for the type of your matrix. That way, you don't have to worry about memory management, since everything about it, will happen automatically.

like image 157
gsamaras Avatar answered Nov 15 '22 13:11

gsamaras