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

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;
make_something(&stack_thing);

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

Leave a Comment