some_id
some_id

Reputation: 29906

Strange malloc issue

I am trying to malloc a float ** that will be accessed like arrayToFill[channel][frame] = 0.f; but I am only able to access it if I do the following code piece, otherwise I get a bad access error.

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

for(int i = 0; i < channelCount; i++)
{
    arrayToFill[i] = (float *) malloc(frameCount * sizeof(float));
}

This just seems completely incorrect.

Upvotes: 2

Views: 145

Answers (2)

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

This seems should be like:

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

for(int i = 0; i < channelCount; ++i)
{
    arrayToFill[i] = (float*) malloc(frameCount * sizeof(float));
}

or, if the number of channels is known ahead and fixed:

#define CHANNEL_COUNT 2

float *arrayToFill[CHANNEL_COUNT];

for(int i = 0; i < CHANNEL_COUNT; ++i)
{
    arrayToFill[i] = (float*) malloc(frameCount * sizeof(float));
}

Upvotes: 4

Kaslai
Kaslai

Reputation: 2505

Well if you only need a rectangular array, you can just write

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

and access the different sections with just a little math

arrayToFill[ x + y * channelCount ];

If you absolutely must have the double subscript, or one of the dimensions is variable, there's no way out of doing what you already have.

Upvotes: 0

Related Questions