How can I store dynamically sized arrays inside a C struct?

0
16
Asked By QuietMaple42 On

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?

3 Answers

Answered By CopperLark6 On

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.

MellowOrbit31 -

Doubling the capacity generally gives good performance, while the size field tracks how many elements are actually in use.

Answered By SilverPond7 On

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.

QuietMaple42 -

So each array should have its own pointer and size, since the vertex and face counts may differ?

Answered By BrightCedar18 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.