I'm new to C and want to represent a mesh with position, rotation, scale, color, and layer fields, plus vertex and face arrays whose lengths are only known at runtime. What is the most memory-efficient way to store and resize those arrays inside the struct?
3 Answers
For arrays whose sizes are known when the mesh is created and remain fixed afterward, you can allocate one block containing the struct and both arrays. That can reduce allocation overhead, but it is more complicated and requires careful alignment and pointer setup. If either array must grow independently, separate allocations are clearer and more practical. C has no built-in dynamic array type, so a small helper structure containing `data`, `length`, and `capacity` is often the cleanest solution.
When an array needs to grow, use realloc. Keep both a current length and a capacity so you do not reallocate every time an element is added. Usually, doubling the capacity when it is full gives good performance. Assign realloc to a temporary pointer first so the original allocation is not lost if the operation fails: `float *tmp = realloc(mesh->vertices, new_capacity * sizeof mesh->vertices[0]); if (tmp != NULL) { mesh->vertices = tmp; mesh->vertex_capacity = new_capacity; }` Remember that realloc may move the data, so any pointers into the old array can become invalid.
Store pointers instead of fixed-size arrays, along with a length for each one. Allocate the arrays with malloc or calloc, and free them when the mesh is destroyed. For example: `struct mesh { float px, py, pz; float rx, ry, rz; float sx, sy, sz; char *color; int layer; float *vertices; size_t vertex_count; int *faces; size_t face_count; };` The two arrays can have separate lengths if their sizes are unrelated.
That makes sense. I’ll track both lengths and make sure both allocations are released when the struct is no longer needed.

Doubling capacity is a good general-purpose strategy. If the final size is known ahead of time, allocating that size once is more efficient.