Better variant of getting the output dinamically-allocated array from the function?

Posted by Raigomaru on Stack Overflow See other posts from Stack Overflow or by Raigomaru
Published on 2010-04-05T09:34:13Z Indexed on 2010/04/05 9:43 UTC
Read the original article Hit count: 116

Filed under:
|
|

Here is to variants. First:

int n = 42;

int* some_function(int* input)
{
    int* result = new int[n];
    // some code
    return result;
}

void main()
{
    int* input = new int[n];
    int* output = some_function(input);

    delete[] input;
    delete[] output;
}

Here the function returns the memory, allocated inside the function.

Second variant:

int n = 42;

void some_function(int* input, int* output)
{
    // some code
}

void main()
{
    int* input = new int[n];
    int* output = new int[n];
    some_function(input, output);

    delete[] input;
    delete[] output;
}

Here the memory is allocated outside the function.

Now I use the first variant. But I now that many built-in c++ functions use the second variant. The first variant is more comfortable (in my opinion). But the second one also has some advantages (you allocate and delete memory in the same block).

Maybe it's a silly question but what variant is better and why?

© Stack Overflow or respective owner

Related posts about c++

Related posts about pointers