Better variant of getting the output dinamically-allocated array from the function?
- by Raigomaru
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?