我不知道为什么这段代码会出现这个错误。我应该怎么办?错误如下:
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 memberd
. 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 byp
behaves, for most purposes, as ifp
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/