omegasbk
omegasbk

Reputation: 906

Statically initializing array inside struct upon struct initialization

I am trying to build a ring buffer by using statically allocated array (requirement, already built dinamical, later decided to go statical). However, I would like to have a generic ring buffer structure that would enable instantiating different sizes of arrays inside of it. I have this structure:

typedef struct measurementsRingBuffer
{   
    int maxSize;
    int currentSize;
    double measurementsArray[MEAS_ARRAY_CAPACITY];
} measurementsRingBuffer;

I instantiate the structure by:

measurementsRingBuffer buffer = { .maxSize = MEAS_ARRAY_CAPACITY, .currentSize = 0 };

Is there any way I could define array size upon struct instantiation, instead of defining it in structure itself? I does not sound possible, but I will give it a shot.

Upvotes: 0

Views: 182

Answers (1)

2501
2501

Reputation: 25753

You can use a pointer to an array:

typedef struct measurementsRingBuffer
{   
    int maxSize;
    int currentSize;
    double* measurementsArray ;
} measurementsRingBuffer;

double small_array[10];
measurementsRingBuffer small = { .maxSize = 10 , .measurementsArray = small_array } ;

or even a compound literal:

measurementsRingBuffer small = { .maxSize = 10 , .measurementsArray = ( double[10] ){ 0 } } ;

Note that the if compound literal is defined outside of a body of a function, it has static storage duration.

Upvotes: 6

Related Questions