Which would be the preferred way of passing information back, created in a function?
A)
create_b_from_a(... a, struct b *my_b) { ... }
int main() {
struct b my_b;
... define and create a ...
create_b_from_a(a, &my_b);
... work on b ...
}
B)
struct st *create_b_from_a(... a)
{
struct st *my_b = malloc(sizeof *my_b);
...
}
int main()
{
struct b *my_b = create_b_from_a(a);
... work on b ...
free(b);
}
I think I remember something like ‘avoid malloc when possible’ but on the other hand B looks more modern to me. Maybe there are pros/cons to one of the approaches that I am not aware of?
Don’t forget that structs are values, so you are not restricted to those two. You can also do:
This can also lead to cleaner code, since it’s more straight-forward, not spending so much code on (micro) management.
And of course, if the compiler decides that on the target architecture actually passing a structure on the stack is horribly in-efficient, there are optimizations that target this pattern.