c - 错误: Invalid use of flexible array member

标签 c arrays struct flexible-array-member

我不知道为什么这段代码会出现这个错误。我应该怎么办?错误如下:

Invalid use of flexible array member

在这一行:

new_buffer->array_msg =array;

这里是较大的代码部分:

   typedef struct buffer {
    int size;
    int T;
    int D;
    int msg_presenti;

    pthread_cond_t not_full;
    pthread_cond_t not_empty;
    pthread_mutex_t mutex;
    msg_t * array_msg[];

} buffer_t;

buffer_t * buffer_init(unsigned int maxsize){
    buffer_t * new_buffer = malloc( sizeof(buffer_t) + maxsize * sizeof(msg_t) );

    msg_t * array[maxsize];
    new_buffer->array_msg =array;
    new_buffer->size=maxsize;
    return new_buffer;
}
// deallocazione di un buffer

最佳答案

这一行足以为您的结构和灵活数组成员分配空间:

buffer_t * new_buffer = malloc( sizeof(buffer_t) + maxsize * sizeof(msg_t *) );
                                ^                  ^
                                1                  2

1 将为 struct 分配内存,而 2 将为灵活数组成员分配空间,因此你的函数应该是这样的:

buffer_t * buffer_init(unsigned int maxsize)
{
    buffer_t * new_buffer = malloc( sizeof(buffer_t) + maxsize * sizeof(msg_t) );

    new_buffer->size=maxsize;
    return new_buffer;
}

如果我们查看 draft C99 standard 6.7.2.1 结构和 union 说明符段落 17 给出了以下示例:

EXAMPLE After the declaration:

struct s { int n; double d[]; };

the structure struct s has a flexible array member d. A typical way to use this is:

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

and assuming that the call to malloc succeeds, the object pointed to by p behaves, for most purposes, as if p had been declared as:

struct { int n; double d[m]; } *p;

(there are circumstances in which this equivalence is broken; in particular, the offsets of member d might not be the same).

关于c - 错误: Invalid use of flexible array member,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20239532/

相关文章:

arrays - Matlab - 从矩阵中删除包含0的行和列

c++ - 任意结构上的 set_union - 我哪里出错了?

c - 返回部分结构

javascript - JSON 数组响应中的总和值

python-3.x - Python 2 到 Python 3 结构包问题

c++ - C/C++结构问题

c - 使用X11(GTK,GDK)功能从C发送键组合

python - 将 C 数组移植到 Python

c - 字符串在 C 中意外移动

python - 如何替换 4 维数组中的值?