[英]invalid use of flexible array -flexible struct array as a member of another struct
我開始學習C中結構的使用。它具有挑戰性和樂趣。 不用說我遇到了一個我似乎無法弄清楚的問題。 我正在嘗試將靈活的struct數組作為另一個struct的成員,但我收到一個錯誤:
無效使用靈活數組
我究竟做錯了什么?
#define NUM_CHANNELS 4
struct channelStruct {
float volume;
uint mute;
};
struct enginestruct
{
float bpm;
int synctimeinbeats;
int synctimeinsamples;
int currentbeat;
int oneBeatInSamples;
int samplerate;
struct channelStruct channels[];
};
struct enginestruct engine, *engineptr;
struct channelStruct channel, *channelptr;
-(void) setupengine
{
engineptr = &engine;
engineptr->oneBeatInSamples = 22050;
engineptr->samplerate = 44100;
struct channelStruct *ch = (struct channelStruct *) malloc (
NUM_CHANNELS*sizeof(struct channelStruct) );
//error occurs here
engineptr->channels = ch;
}
編輯1
這是我想要達到的目標
編輯2 *
好的,所以我似乎正在接近以錯誤的方式創建一個可變大小的struct數組。 我有兩件事正在嘗試。 我知道的第一個肯定是有效的。 第二個我願意,如果有人能夠理智地檢查它。 我還在學習指針,想知道A是否與B相同.B是我的首選方法,但我不知道它是否正確。 我對a有信心,因為當我調試頻道時,我看到頻道[0],頻道[1]頻道[2]等。但我對B不太自信,因為當我調試它時我只看到一個地址到內存和列出的通道結構的變量。
一種
// pretty sure this is o.k to do but I would prefer
// not to have to set the size at compile time.
struct enginestruct
{
float bpm;
int synctimeinbeats;
int synctimeinsamples;
int currentbeat;
int oneBeatInSamples;
int samplerate;
channel channels[NUM_CHANNELS]; //is this technically a pointer?
};
乙
//I'm not sure if this is valid. Could somebody confirm for me if
//it is allocating the same amount of space as in A.
struct enginestruct
{
float bpm;
int synctimeinbeats;
int synctimeinsamples;
int currentbeat;
int oneBeatInSamples;
int samplerate;
channel *channels;
};
//This only works if channel in the engine struct is defined as a pointer.
channel * ar = malloc(sizeof(*ar) * NUM_CHANNELS);
engineptr->channels = ar;
**編輯3 ****
是的,他們是一樣的。 不知道什么時候你會使用一個而不是另一個
channel channels[NUM_CHANNELS];
等於:)
struct enginestruct
{
float bpm;
int synctimeinbeats;
int synctimeinsamples;
int currentbeat;
int oneBeatInSamples;
int samplerate;
channel *channels;
};
channel * ar = malloc(sizeof(*ar) * NUM_CHANNELS);
engineptr->channels = ar;
編輯
我想我現在記得問題是什么。 當你聲明一個具有靈活數組的結構作為它的最后一個成員時,它正在做一些與你想象的完全不同的事情。
struct channelStruct channels[];
不是指針,它是一個與結構相鄰的就地數組。
打算使用它的方法是將結構放在現有的塊存儲器上。 例如,當您擁有包含可變長度數據的數據包時,這在網絡中很有用。 所以你可以這樣做:
struct mydata {
// various other data fields
int varDataSize;
char data[];
}
當您收到數據包時,您將指向數據的指針轉換為mydata
指針,然后varDataSize
字段會告訴您已經獲得了多少。 就像我說的那樣,要記住的是它是一個連續的內存塊, data
不是指針。
舊答案:
我認為只允許符合C99標准。 嘗試使用-std=c99
標志進行編譯。
另外,請參閱此線程, struct中的Variable數組
另見SO帖子: C中的靈活陣列成員 - 不好?
我不是這個C功能的專家,但我的常識告訴我,你不能定義struct enginestruct
類型的對象,只能指針。 這涉及以下行中的engine
變量:
struct enginestruct engine,*engineptr;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.