在C中初始化结构数组

贝尔金鱼

我有以下结构

typedef struct {
    int buf[BUF_SIZE]; // the buffer
    size_t len; // number of items in the buffer
    pthread_mutex_t mutex; // needed to add/remove data from the buffer
    pthread_cond_t can_produce; // signaled when items are removed
    pthread_cond_t can_consume; // signaled when items are added
};

最初我只是按如下方式对其进行初始化

buffer_t buffer = {
    .len = 0,
    .mutex = PTHREAD_MUTEX_INITIALIZER,
    .can_produce = PTHREAD_COND_INITIALIZER,
    .can_consume = PTHREAD_COND_INITIALIZER
};

尽管我想使用这些值初始化buffer_t数组,但是我不确定如何正确地执行该操作。

就像是

buffer_t buffer[NUM_ARRAY] = {
    .len = 0,
    .mutex = PTHREAD_MUTEX_INITIALIZER,
    .can_produce = PTHREAD_COND_INITIALIZER,
    .can_consume = PTHREAD_COND_INITIALIZER
};

(我意识到这是不正确的)

编辑:我最终使用

buffer_t buffers[NUM_THREADS];

for (i = 0, i < 3, i ++) {
       buffers[i] = (buffer_t) {
                .len = 0,
                .mutex = PTHREAD_MUTEX_INITIALIZER,
                .can_produce = PTHREAD_COND_INITIALIZER,
                .can_consume = PTHREAD_COND_INITIALIZER
            };  
}
dbush

如果NUM_ARRAY不是太大,您可以执行以下操作:

#define NUM_ARRAY 3

buffer_t buffer[NUM_ARRAY] = {
    { {0}, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER},
    { {0}, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER},
    { {0}, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER}
};

或者,您可以像下面这样显式地编写代码:

buffer_t buffer[NUM_ARRAY];
int i;
for (i=0; i<NUM_ARRAY; i++) {
    memset(buffer[i].buf, 0, sizeof(buffer[i].buf));
    buffer[i].len = 0;
    buffer[i].mutex = PTHREAD_MUTEX_INITIALIZER;
    buffer[i].can_produce = PTHREAD_COND_INITIALIZER;
    buffer[i].can_consume = PTHREAD_COND_INITIALIZER;
}

编辑:

因此,看起来PTHREAD_MUTEX_INITIALIZERand和PTHREAD_COND_INITIALIZER宏不能在这样的赋值中使用,因为它只能在初始化以及包含{}字符中使用。

因此,您需要像其他人建议的那样使用初始化语法:

buffer_t buffer[NUM_ARRAY];
int i;
for (i=0; i<NUM_ARRAY; i++) {
    buffer[i] = (buffer_t) {
        0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER
    };
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章