Return of arrays and structures,...
Doug Gwyn
gwyn at smoke.brl.mil
Fri Apr 19 02:15:20 AEST 1991
In article <1991Apr17.173914.3683 at milton.u.washington.edu> rburgess at milton.u.washington.edu (Rick Burgess) writes:
>Apparently values of structures can be returned from functions under the ANSI
>standard...?
Yes; this has been existing practice in UNIX C compilers since around 1978.
>Can Arrays also?
No.
>Aren't structures essentially a pointer constant just like arrays?
No, they never were interpreted as pointers, unlike array names in most
expression contexts.
>When you pass a structure and not a structure pointer aren't you gonna end up
>with the version modified in the routine it is passed to just like with
>arrays?
No, structure arguments and return value are passed "by value", just like
every other type in C. To modify a structure in the caller one would have
to pass an explicit pointer to it.
>Can anyone give some logical or anectdotal suggestions on when pointers are
>well used, when structures and arrays themselves, and when it is actually
>good to return either or both of these rather than just letting them be
>modified directly by the subroutine?
>(I know, I should probably take a compsci course, right?)
No, but you SHOULD read a good C textbook (I recommend K&R 2nd Edition).
Prototypical examples of functions that return structs are:
struct complex { double re, im; };
extern struct complex c_add( struct complex a, struct complex b );
and
typedef struct { short x, y; } point;
typedef struct point vector;
extern point p_add( point p, vector v );
For really large structures it is usually more efficient, albeit less
convenient, to use pointers.
More information about the Comp.lang.c
mailing list