Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uunet!taumet!steve From: steve@taumet.COM (Stephen Clamage) Newsgroups: comp.lang.c Subject: Re: Function returning Structure: How does it work? Keywords: structure, struct Message-ID: <231@taumet.COM> Date: 31 May 90 15:43:08 GMT References: <1990May28.215331.29333@agate.berkeley.edu> <18222@well.sf.ca.us> <8048@crdgw1.crd.ge.com> Reply-To: steve@taumet.UUCP (Stephen Clamage) Distribution: usa Organization: Taumetric Corporation, San Diego Lines: 27 In article <8048@crdgw1.crd.ge.com> larocque@jupiter.crd.ge.com (David M. LaRocque) writes: >One instance I thought of that one may want to use a function that >returns a structure is as an alternative to malloc. > >struct point { int x; int y; }; >struct point makepoint(int x, int y); >struct rect { struct point pt1; struct point pt2; }; >struct rect screen; >screen.pt1 = makepoint(0, 0); In this example, the return from makepoint() is copied to a static (in this case global) variable. Following the call to makepoint, what it actually returned is irrelevant, since it can no longer be referenced. The copy stays where it is (in this case, globally available until the end of the program). If you had a local struct assigned the return from makepoint(), that local struct would contain the value until it's containing function returned, at which time it would disappear. Think about a function returning an int. Where is the int located? Can it be clobbered later? Any function return value must be used (copied) immediately as part of the expression calling the function. This is as true for structs as for ints. -- Steve Clamage, TauMetric Corp, steve@taumet.com