Home > Net >  What to do with output from function returning double pointer
What to do with output from function returning double pointer

Time:01-10

I have this dilemma. fruit is a struct.

fruit** func2create(const int N, const int M)
{
    fruit **arr;
    arr = new fruit*[N];

    for(int i = 0; i < N; i  )
    {
        arr[i] = new fruit[M];
    }

    return arr;
}

This function returns a pointer pointing to a 2d array, at least that is what I think it does.

Now, having this function, how do I actually make a 2d array using it?

CodePudding user response:

I wouldn't use the notation with double pointers. It is sure to result in a memory leak somewhere since it is not clear who will cleanup the memory. In C I would use one of the following methods (using either std::array, or std::vector). Which is also more in line with the C core guidelines regarding the use of new/delete (https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines look for anything about pointers and/or new/delete)

#include <array>
#include <vector>

struct fruit
{
};

// sizes know at compile time then use a function template 
template<std::size_t N, std::size_t M>
auto func2create()
{
    // create initialized array
    std::array<std::array<fruit, M>, N> fruits{};
    return fruits;
}

// for runtime sizes use std::vector
// note I don't use ints (they can have negative values
// I don't want to test for that)
auto func2create(const std::size_t n, const std::size_t m)
{
    // create n rows of m fruits
    std::vector<std::vector<fruit>> fruits(n, std::vector<fruit>(m));
    return fruits;
}

int main()
{
    // compile time allocate fruits
    {
        auto fruits = func2create<4, 4>();
        auto fruit = fruits[1][1];
    }

    // runtime alloacted fruits
    {
        auto fruits = func2create(4ul, 4ul);
        auto fruit = fruits[1][1];
    }
    
    return 0;
}

CodePudding user response:

For example:

int N = ...;
int M = ...;
fruit** arr = func2create(N, M);

for(int i = 0; i < N;   i) {
    for(int j = 0; j < M;   j) {
        // use arr[i][j] as needed...
    }
}

... 

for(int i = 0; i < N;   i) {
    delete[] arr[i];
}
delete[] arr;
  •  Tags:  
  • Related