如何动态分配单维数组或二维数组,具体取决于值1还是2?
此数组需要保留frameCount
个浮点数,但需要在1或2个通道之间分配。第一个维度是通道计数,第二个维度是帧数。如果有2个频道,frameCount
将在2个维度之间分割,例如[channelNumber] [frameNumber]
我有以下代码,但我认为它不起作用。
float ** arrayToFill = (float **)malloc((frameCount*channelCount)*sizeof(float));
我的数组在调试器中看起来像这样
我需要将一个浮动**传递给一个函数,以便它可以按如下方式填充数组
- (OSStatus) readFloatsConsecutive:(SInt64)numFrames intoArray:(float**)audio withOffset:(long)offset
{
OSStatus err = noErr;
if (!mExtAFRef) return -1;
int kSegmentSize = (int)(numFrames * mExtAFNumChannels * mExtAFRateRatio + .5);
if (mExtAFRateRatio < 1.) kSegmentSize = (int)(numFrames * mExtAFNumChannels / mExtAFRateRatio + .5);
AudioBufferList bufList;
UInt32 numPackets = numFrames; // Frames to read
UInt32 samples = numPackets * mExtAFNumChannels;
UInt32 loadedPackets = numPackets;
short *data = (short*)malloc(kSegmentSize*sizeof(short));
if (!data) {
NSLog(@"data is nil");
goto error;
}
bufList.mNumberBuffers = 1;
bufList.mBuffers[0].mNumberChannels = mExtAFNumChannels;
bufList.mBuffers[0].mData = data; // data is a pointer (short*) to our sample buffer
bufList.mBuffers[0].mDataByteSize = samples * sizeof(short);
@synchronized(self) {
err = ExtAudioFileRead(mExtAFRef, &loadedPackets, &bufList);
}
if (err) goto error;
if (audio) {
for (long c = 0; c < mExtAFNumChannels; c++) {
if (!audio[c]) continue;
for (long v = 0; v < numFrames; v++) {
if (v < loadedPackets) audio[c][v+offset] = (float)data[v*mExtAFNumChannels+c] / 32768.f;
else audio[c][v+offset] = 0.f;
}
}
}
error:
free(data);
if (err != noErr) return err;
if (loadedPackets < numFrames) mExtAFReachedEOF = YES;
mRpos += loadedPackets;
return loadedPackets;
}
答案 0 :(得分:2)
您的malloc语句是正确的,但您的类型错误。 Malloc返回一个地址(即指针),该地址处的东西是一系列浮点数中的第一个。也就是说,它返回一个指向float的指针。
试
float * arrayToFill = malloc ( (frameCount * channelCount) * sizeof( float ));
如果你真的需要指针指针,那么你可能需要像这样的malloc:
float ** arrayToFill = malloc(frameCount * sizeof(float *));
for(i=0;i<frameCount;i++)
arrayToFill[i] = malloc(channelCount * sizeof(float));
但这只是猜测。您正在调用的功能应明确传递的内容。