[英]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.
我听起来不太可能,但我会试一试。
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. 请注意,如果复合文字在函数主体之外定义,则它具有静态存储持续时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.