2013-11-27 48 views
-3

我不知道爲什麼這段代碼會給出這個錯誤。我該怎麼辦?錯誤如下:錯誤:使用靈活的陣列成員無效

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 
+3

投票重新提出問題現在有足夠的信息來回答。 –

回答

1

這條線就足以爲您的分配空間結構和柔性陣列成員:

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

1將分配內存結構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結構聯合說明符段給出以下示例:

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).

相關問題