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:
我试图通过使用静态分配的数组(要求,已经建立的dinamical,后来决定去静态)来构建一个环形缓冲区。但是,我希望有一个通用的环形缓冲区结构,可以在其中实例化不同大小的数组。我有这个结构:
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.
有没有什么办法可以在结构实例化时定义数组大小,而不是在结构本身中定义它?我听起来不太可能,但我会试一试。
1 个解决方案
#1
5
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.
请注意,if复合文字是在函数体外定义的,它具有静态存储持续时间。
#1
5
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.
请注意,if复合文字是在函数体外定义的,它具有静态存储持续时间。