Sanchke Dellowar Sanchke Dellowar - 6 months ago 22
C Question

In C, how would I choose whether to return a struct or a pointer to a struct?

Working on my C muscle lately and looking through the many libraries I've been working with it's certainly gave me a good idea of what is good practice. One thing that I have NOT seen is a function that returns a struct:

something_t make_something() { ... }

From what I've absorbed this is the "right" way of doing this:

something_t *make_something() { ... }
void destroy_something(something_t *object) { ... }

The architecture in code snippet 2 is FAR more popular than snippet 1. So now I ask, why would I ever return a struct directly, as in snippet 1? What differences should I take into account when I'm choosing between the two options?

Furthermore, how does this option compare?

void make_something(something_t *object)


When something_t is small (read: copying it is about as cheap as copying a pointer) and you want it to be stack-allocated by default:

something_t make_something(void);

something_t stack_thing = make_something();

something_t *heap_thing = malloc(sizeof *heap_thing);
*heap_thing = make_something();

When something_t is large or you want it to be heap-allocated:

something_t *make_something(void);

something_t *heap_thing = make_something();

Regardless of the size of something_t, and if you don’t care where it’s allocated:

void make_something(something_t *);

something_t stack_thing;

something_t *heap_thing = malloc(sizeof *heap_thing);