Question

I have a specific application written in C that needs to be memory efficient. It is collecting statistics, so I need to be able to "turn on/off" certain fields in run-time to minimize the memory consumption. I know you can define conditional struct fields using macros but that is compile-time if I'm not mistaken, is there a possible way of doing this in C in run-time?

Example:

input :

collect (A,B)

will result in a struct like this:

struct statistics{
double A;
double B;
};

but input:

collect (A,B,C)

will result in a struct like this:

struct statistics{
double A;
double B;
double C;
};
Was it helpful?

Solution

Its not possible to turn-off certain fields inside the struct at run-time. You can however have a pointer that points to a dynamically allocated array of doubles that can represent multiple fields. For example:

#include <stdio.h>
#include <stdlib.h>

struct stats
{
    size_t number_of_doubles;
    double* data;
};

void make_stats(struct stats* pStats)
{
    pStats->number_of_doubles = 3;
    pStats->data = (double*) malloc(pStats->number_of_doubles * sizeof(double));
}

void delete_stats(struct stats* pStats)
{
    free(pStats->data);
}

int main()
{
    struct stats foo;

    make_stats(&foo);

    foo.data[0] = 3.0;
    foo.data[1] = 5.0;
    foo.data[2] = 7.0;

    delete_stats(&foo);    
    return 0;
}

OTHER TIPS

Instead of the usual array of structs (AoS):

struct statistics{
    double A;
    double B;
    double C;
};

struct statistics my_statistics = malloc(1000000 * sizeof(my_statistics[0]));

my_statistics[0].A = 1;
my_statistics[0].B = 2;
my_statistics[0].C = 3;

you could switch to a struct of arrays (SoA):

struct statistics{
    double *A;
    double *B;
    double *C;
};

struct statistics my_statistics;

my_statistics.A = using_A ? malloc(1000000 * sizeof(my_statistics.A[0])) : NULL;
my_statistics.B = using_B ? malloc(1000000 * sizeof(my_statistics.B[0])) : NULL;
my_statistics.C = using_C ? malloc(1000000 * sizeof(my_statistics.C[0])) : NULL;

my_statistics.A[0] = 1;
my_statistics.B[0] = 2;
my_statistics.C[0] = 3;

There is no way to alter the size of a struct at runtime. The size of a struct is built into the executable's instructions whenever you allocate them on the stack or on the heap. As another example, sizeof of a struct is available at compile time, so it can not be altered at runtime.

Of course, you can have custom structs with a custom memory manager to do that, but it's not built right into the language.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top