Question about return values of type struct

Troy Holly u-tholly at wasatch.utah.edu
Sat Jul 29 14:34:41 AEST 1989


What happens when a procedure returns an auto variable of type struct?
The variable in question is declared in the procedure that returns it.
Am I right in thinking that auto variables "exist" on the stack only
during the time that the procedure is active?  The code in question
looks something like this:

type def struct {
	double *ptr1;
	double *ptr2;
	int n;
	int m;
} mystruct;

mystruct copyfoo(foo1) mystruct foo1; {
	
	mystruct foo2;
	int i;
	
	foo2.ptr1 = malloc( m * sizeof(double) );
	for ( i = 0; i < foo1.m; i++ )
		foo2.ptr1[i] = foo1.ptr1[i];
	.
	.
	.
	return ( foo2 );
}

main () {

	mystruct foo3, foo4;

	.
	.	(assign foo4 some values)
	.
	foo3 = copyfoo(foo4);
	.
	.
	.
}

I am worried about this code.  I have more or less inherited it.  Does
the assignment to foo3 in main() need to be done with pointers, i.e.,  
should copyfoo() return a pointer to struct instead of a struct?  Like
I said above, I am worried that the struct in copyfoo() that is returned
will be overwritten on the stack.

Thanks in advance,

Troy -


	
	



More information about the Comp.lang.c mailing list