How can I store dynamically sized arrays inside a C struct?
Asked by
pixel_art_class
I'm new to C and want to define a mesh struct containing position, rotation, scale, color, layer, and two arrays: one for vertex data and one for faces. The arrays won't always have the same length, so fixed-size declarations such as float vertices[99] and int faces[99] aren't suitable. What's the most memory-efficient way to let each mesh hold a variable number of elements and grow when necessary?
Answers
A typical definition would look like this: 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; }; Then allocate the arrays based on the counts you need, for example with calloc(count, sizeof *mesh.vertices). This avoids reserving unused space and lets the two arrays have independent sizes.
Reply to this answer
Use pointers for the arrays and keep their current lengths in the struct. Allocate each array with malloc or calloc, resize it with realloc when it needs to grow, and free both arrays when the mesh is destroyed. Keep the old pointer until realloc succeeds so you don't lose the original allocation if memory is unavailable.
Reply to this answer
If the arrays grow repeatedly, store both a size and a capacity for each one. When size reaches capacity, call realloc and increase capacityโdoubling it is a common strategy. That avoids reallocating and copying the data on every append. If the final sizes are known and never change, a single allocation containing the struct and array storage can reduce allocation overhead, but separate allocations are usually simpler and flexible.
RookToBishop: Doubling the capacity generally gives good performance, while the size field tracks how many elements are actually in use.
Reply to this answer
Add your answer
Answers are reviewed before publication.
pixel_art_class: So each array should have its own pointer and size, since the vertex and face counts may differ?