do I need to allocate space twice?

Jim Klavetter jjk at jupiter.astro.umd.edu
Sat Mar 30 08:03:41 AEST 1991


I have a function which returns a pointer of type double.  This is
really an "array".  Should the main program or the function allocate
the space?  Does it matter?  Certainly, I don't need to allocate space
twice, right?

To make this clear, here is a simple example:  add two arrays:

double *addarray(a, b, n)
double *a, *b;
int n;
{
	int i;
	double *result;

	for(i=0; i<n; i++)
		result[i]=a[i]+b[i];
	return(result);
}

with the main program having the fragment:

double *sum, *addarray();
...
sum=addarray(x, y, num);
...

The question is where do I allocate the storage for sum?  It seems to
me that if I do it in the function, then I can just return the pointer
and that is all, since the space will be allocated.  Is this correct?
As a followup, if I ever want to free the space, and it is true that I
allocate it in the function, then can I free the pointer from main?

As an aside, don't worry about code optomization or even bugs:  I just
made it up on the fly and I use it to get the idea across.  If I've
made any conceptual mistakes, on the other hand, please let me know?

jjk at astro.umd.edu also for Athabasca and Reudi
Jim Klavetter
Astronomy
UMD
College Park, MD  20742



More information about the Comp.lang.c mailing list