0

如何根据值 1 或 2 动态分配一维数组或二维数组?

该数组需要保存frameCount许多浮点数,但需要拆分为 1 或 2 个通道。第一个维度是通道数,第二个维度是帧数。如果有 2 个通道,frameCount则在 2 个维度之间进行拆分,例如 [channelNumber] [frameNumber]

我有以下代码,但我认为它不起作用。

float ** arrayToFill = (float **)malloc((frameCount*channelCount)*sizeof(float));

我的数组在调试器中看起来像这样

在此处输入图像描述

我需要将 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;
 }
4

1 回答 1

2

您的 malloc 语句是正确的,但您的类型是错误的。Malloc 返回一个地址(即指针),该地址处的内容是一系列浮点数中的第一个。也就是说,它返回一个指向浮点数的指针。

尝试

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

但这只是一个猜测。您正在调用的函数应该清楚传递它的内容。

于 2012-07-22T06:03:41.587 回答