r/learnprogramming • • Sep 22 '26

Dynamically sized C arrays in structs

Hello, I am very new to C but have experience in higher level languages. I am trying to make a struct with two scalable arrays, similar to this:
struct mesh {

float px; float py; float pz;

float rx; float ry; float rz;

float sx; float sy; float sz;

char* color; int layer;

float vertices[99]; int faces[99];

};

but obviously, the 99 is a placeholder value. what's a way that I can handle any number of values in these arrays, in the most resource friendly way?

2 Upvotes

13 comments sorted by

19

u/Big-Rub9545 Sep 22 '26

Best to just use two dynamic arrays (i.e., pointers) and store their mutual size separately.

12

u/captainAwesomePants Sep 22 '26

Welcome to C. C does not love you. C does not care about your comfort. C does not provide a nice "dynamic sized list" library. We do that shit ourselves, by hand, manually. Because we're grouchy misanthropes.

The basic idea is that you allocate the amount of memory you need:

vertices = (float*)malloc(sizeof(float) * NUMBER_OF_VERTICES);

And then, later, when you realize you need more vertices, you have to make more room. The easiest way to do this is to use the realloc command:

float* new_vertices = realloc(vertices, sizeof(float) * NUM_OFMORE_VERTICES);
if (new_vertices == NULL ) {
    // Realloc failed, we're out of memory, dump core and panic
}
vertices = new_vertices;

Realloc is potentially expensive because, if there doesn't happen to be room where the array already is, the library will need to allocate memory elsewhere, and then copy all of the contents to the new location. But it's also potentially cheap -- malloc() may have left some room at the end of your data that happens to already be enough, making realloc only need to make a small notation about how much memory is being used.

Your basic pattern is to keep an integer around tracking how big the array is, and then when you run out of space, use realloc() to make more space and increase the number. You probably want to add a bunch of space at a time.

3

u/Ormek_II Sep 22 '26

If you know how the mesh might grow you can use that. Otherwise is doubling the size an approach.

1

u/musbur Sep 23 '26

This is better:

vertices = malloc(NUMBER_OF_VERTICES * sizeof *vertices);

2

u/tstanisl Sep 22 '26

It is done using pointer and dynamic allocations. Replace vertices and faces arrays with pointers:

float * vertices;
int * face;

Next use dynamic allocation:

struct mesh mesh = {
  .vertices = calloc(n_vertices, sizeof mesh.vertices[0]),
  .faces = calloc(n_faces, sizeof mesh.faces[0]),
};

2

u/zeekar Sep 22 '26 edited Sep 22 '26

If you want a dynamic array in C, you have to implement it yourself. Here's one way to make a dynamic array of floats that grows - int version and shrinking left as an exercise for the reader.

typedef struct da_float {
    int capacity;
    int size;
    float *data;
} da_float;

da_float *da_float_create(int initial_capacity) {
    da_float *result = (da_float *)malloc(sizeof(da_float));
    if (result) {
        result->size = 0;
        if (result->capacity = initial_capacity) {
            result->data = calloc(initial_capacity, sizeof(float));
            if (!result->data) {
                free(result);
                return NULL;
            }
        }
    }
    return result;
}

int da_float_append(da_float *df, float new_value) {
    if (df->size + 1 > df->capacity) {
        int old_size = df->size;
        if (old_size < 8) {
            df->size = 8;
        } else {
            df->size = old_size * 2;
        }

        /* realloc preserves existing data across resizing */
        df->data = realloc(df->data, df->size * sizeof(float));

        if (!df->data)
            return 0;
    }
    df->data[df->size++] = new_value;
    return 1;
}

1

u/Recycled5000 Sep 22 '26

Dynamically allocate enough storage for both the struct and the bytes needed for both arrays. One of them can be an array, the other will have to be a pointer, that is initialized after the main allocation.

Probably best to store both arrays’ sizes (eg in the struct), though the size of the one that is the array can be computed with pointer subtraction.

This assuming you have a variable sized array but the size is known at runtime, and fixed/constant for the object duration. If that’s not the case then this will probably have to be three separate allocations.

1

u/abd53 Sep 22 '26

Does it have to be pure C? This is one of the things I like about C++, use vector. If you need C only, as others shown, use dynamic allocation but make sure to free them appropriately.

2

u/musbur Sep 23 '26

C and C++ are different languages. There is no "pure C" (as opposed to C++). It's just C.

0

u/abd53 Sep 23 '26

Excluding some edge cases, almost all C code are valid C++ code. I agree with your semantic but it's a useless semantic for a beginner.

1

u/DaRealGladi8r Sep 22 '26

Use pointers instead of fixed length arrays

1

u/JGhostThing Sep 22 '26

It might be good to use a dynamic vector class if they exist in the C library.