【发布时间】:2010-12-07 17:31:00
【问题描述】:
我开始学习在 C 中使用结构。它具有挑战性和乐趣。不用说我遇到了一个我似乎无法弄清楚的问题。我正在尝试将灵活的结构数组作为另一个结构的成员,但出现错误:
灵活数组的使用无效
我做错了什么?
#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
这就是我正在努力实现的目标
flexible length struct array inside another struct using C
编辑 2*
好的,所以我似乎以错误的方式接近创建可变大小的结构数组。我有两件事正在尝试。我知道的第一个肯定有效。第二个我想如果有人可以为我检查一下。我仍在学习指针,想知道 A 是否与 B 相同。B 将是我的首选方法,但我不知道它是否正确。我对 a 很有信心,因为当我调试通道时,我会看到 channel[0]、channel[1]channel[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?
};
B
//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;
【问题讨论】:
-
您使用的是什么平台和编译器?
-
我使用的是 ios4 和 gcc 4.2。我已经遵循了很多例子,但我就是无法破解它