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

0
0
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?

1 Answer

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.