Saturday, May 16, 2009

A sweet discovery, returning or passing pointers

IN C/c++ programs a common thing is to return values by address

double * return_doubleval()
double *a = new double
*a = 1;
return a;

as opposed to

void return_double(double *a)
if (a==NULL)
a = new double ;
*a =1;

because the second idea does not work
we need to send in double **a and do (*a) = new double if we want the pointer address also to be updated in the calling function

BTW, the idea of allocating memory and having the caller delete the memory is a bad bad idea
nevertheless, sometimes we dont know the length of the array we want to allocate and only the function that is called knows an answer to it, and this becomes mandatory

No comments:

Post a Comment