0

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.

4
  • With static storage duration? Commented Jul 4, 2016 at 9:49
  • 1
    I'm not sure but if you use a pointer instead of an array, and if the array is the last member of your structure, then I guess you can decide of its size when you allocate the memory. Anyway instead of having sizeof(measurementsRingBuffer) you will have the cumulated size of all the members plus n*sizeof(double) with n the size of your array Commented Jul 4, 2016 at 9:50
  • It is real-time system with strict memory consumption requirements. It needs to know how much memory will be needed. Commented Jul 4, 2016 at 9:50
  • If the array is defined before the structure is defined, you could simply use sizeof(the_array) as array size. Commented Jul 4, 2016 at 12:47

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! This sounds correct, gonna try it. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.