I stumbled upon a really nice trick in [mathc]:
struct vec3
{
double v[3];
};
[mathc]:
https://github.com/felselva/mathc
Maybe it's an old trick, but it was new to me.
When writing a math library in C, you often deal with vectors and
matrices -- in other words, arrays of a fixed size. And it would be
really nice if you were able to write code like that:
struct vec3 foo = {.v = {1, 2, 3}}, bar;
bar = vec3_normalized(foo);
That function `vec3_normalized()` takes a vector as an argument,
normalizes it, and returns a *new* vector.
If you use plain arrays in C, you can't do that. You'd have to call
`malloc()` and allocate some memory on the heap. Of course, you'd have
to free this memory later on. And there you have it, the burden of
memory management.
But! C has this peculiar property that you can return a struct from a
function. So ... by simply wrapping your fixed-sized arrays in a struct,
you can create a new array in a function and return it. No `malloc()`,
no `free()`. Neat.