Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!ames!eos!shelby!neon!Gang-of-Four!dkeisen From: dkeisen@Gang-of-Four.Stanford.EDU (Dave Eisen) Newsgroups: comp.lang.c Subject: Re: Function returning Structure: How does it work? Keywords: structure, struct Message-ID: <1990May28.235336.5338@Neon.Stanford.EDU> Date: 28 May 90 23:53:36 GMT References: <1990May28.215331.29333@agate.berkeley.edu> Sender: news@Neon.Stanford.EDU (USENET News System) Distribution: usa Organization: Sequoia Peripherals Lines: 37 In article <1990May28.215331.29333@agate.berkeley.edu> m100-2ai@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@Gang-of-Four.Stanford.EDU Office: (415) 967-5644 1447 N. Shoreline Blvd. Mountain View, CA 94043