[ back to toc ]

Functions and structures

Date: 2002/03/19 14:20

Q:
I'm trying to write a funtion which can both take a structure as a
parameter and return a structure. I would be happy with it just taking
int values. But is it possible for a function to return a structure
(rather than and int or char etc) that has been defined outside of main?
any help or ideas would be great.

*NAME-DELETED*
A:
Dear *NAME-DELETED*,
in language C you can not return a whole structure. You can however
allocate space for the structure calling malloc, set the structure fields
and then return a pointer to the allocated structure. In this case,
however the caller has to call free to release the memory when it is not
needed any more.

It is also possible not to 'return' the structure but get a pointer to an
already allocated structure (which may perhaps be a local variable in a
function) and fill in the fields of the structure through the pointer.
This second is the usual approach.

Just as you can not return, you also can not accept a structure as a
parameter. You can however accept a pointer to a structure as a parameter.
In this case the called function's responsibility not to alter the
structure, unless that is the specific aim of the function.

Regards,
Peter

[ back to toc ]