Which of the following is a good practice?


Option I

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <math.h>
#include <iostream>
#include <stdio.h>

double **fun1(double *x, double *y);
int main()
{
double *x,*y, **w;
// here declare and allocate x and y

w = fun1(x,y)  // call fun1

delete [] x;
delete [] y;
delete [] *w;
delete [] w

}

double **fun1(double *x, double *y)
{
double **z;

allocate memory to z;

do some stuff here


return z;

}



Option II
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <math.h>
#include <iostream>
#include<stdio.h>

void fun1(double *x, double *y,double **zOutput);
int main()
{
double *x,*y,**w;
// here declare and allocate x , y and w

fun1(x,y,w)  // call fun1

do some stuff here

delete [] x;
delete [] y;
delete [] *w;
delete [] w;

}

void fun1(double *x, double *y, double **z)//here z holds the output like passing by reference
{

do some stuff here

}



Hello guys, I need to implement either of the above options for my project. Which of the two options is good and safe practice for memory handling and performance.
between returning a value and using an "out" parameter, returning a value almost always makes a lot more sense. Neither example is even remotely safe, though, start by using vectors.
closed account (3qX21hU5)
Really it all depends on what you are trying to do. There will be some functions that need to alter something directly and some that need to return something from a function. There isn't really a one style fits all.

But like Cubbi pointed out I would suggest moving towards vectors. Also another pointer is when using pointers I would highly recommend using std::unique_ptr instead.

Thanks so much Cubbi and Zereo. I will try to consider vectors.
In the second example you do not use return type of the function. Instead of it you declared additional parameter. it is not a good approach because it is not clear who is responsible to allocate memory for this parameter. However sometimes such an approach can be used. For example when you declare function pop of a user-defined container stack in C.
Thanks Vlad!
Topic archived. No new replies allowed.