How does one dynamically allocate either a single dimensional array or a two dimensional array, depending on either the value 1 or 2?
This array needs to hold a frameCount number of floats but split between 1 or 2 channels. The first dimension being the channel count and the second being the number of frames. If there are 2 channels, the frameCount is split between the 2 dimensions, such as [channelNumber] [frameNumber]
I have the following code but I don’t think it is working.
float ** arrayToFill = (float **)malloc((frameCount*channelCount)*sizeof(float));
My array looks like this in the debugger

I need to pass a float ** to a function so it can fill the array with as follows
- (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;
}
Your malloc statement is correct, but your type is wrong. Malloc returns an address, (ie a pointer) and the thing at that address is the first of a series of floats. That is, it returns a pointer to a float.
try
If you really need a pointer pointer, then you probably need to malloc something like this:
But this is just a guess. The function you are calling should be clear on what to pass it.