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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.