Function returning Structure: How does it work?

Dave Eisen dkeisen at Gang-of-Four.Stanford.EDU
Tue May 29 09:53:36 AEST 1990


In article <1990May28.215331.29333 at agate.berkeley.edu> m100-2ai at WEB.berkeley.edu () writes:
>
>STRUCT function(void)
>{
>	STRUCT structure;
>
>	structure.num = 0;
>	/* Set other fields as well */
>	return structure;	
>}
>
>Now, it seems that the storage space for 'structure' has to be allocated
>on the heap (not on stack). 

Why?

C implementations usually allocate automatic variables on the stack, the fact
that it is a structure has nothing to do with this. C is not known for playing
with the heap without the user telling it to.

The only problem lies in returning a struct value. In an implementation that
returns function values in a register, something special must be done
to handle return values larger than will fit in that register. One way to do
this is to return the address of a block of static memory where the struct can 
be found and have the calling function copy the value found there into the struct
the return value of the function is supposed to be assigned to. Of course, this
can lead to a great deal of copying so most of the time you're better off
arranging things for the function to have type STRUCT * instead.




--
Dave Eisen                      	    Home: (415) 323-9757
dkeisen at Gang-of-Four.Stanford.EDU           Office: (415) 967-5644
1447 N. Shoreline Blvd.
Mountain View, CA 94043



More information about the Comp.lang.c mailing list