Blue Sky
Blue Sky

Reputation: 323

Create Dynamic Arrays of Pointers to Structures in C

I have a code like the following, which works fine:

AVFrame *frame = NULL;
open_input(&frame);

where the input argument of open_input is something like: AVFrame **frame;

Now, I want to extend this code to work with an array of frames (say, N frames). I tried the following code but my code stops working after being compiled by gcc in MingW:

int i, N = 3;
AVFrame **frame;
frame = (AVFrame *) malloc(N * sizeof(AVFrame *));
for(i=0;i<N;i++){
   frame[i] = (AVFrame *) malloc(sizeof(AVFrame));
   open_input(&frame[i]);
}

Do you know, what is the problem?

Upvotes: 0

Views: 92

Answers (3)

haccks
haccks

Reputation: 105992

&frame[i] is of type AVFrame **. It seems that open_input is expecting the argument of type AVFrame *.
Change

open_input(&frame[i]);  

to

open_input(frame[i]);   

Here frame[i] is of type AVFrame *.

And also do not cast the return value of malloc.

Upvotes: 0

simonc
simonc

Reputation: 42165

If you want to allocate an array of frames, you could simply do

AVFrame *frame = malloc(N * sizeof(*frame));

accessing each element using frame[index]

A pointer to a pointer to AVFrame would only be required if you wanted an array of AVFrame arrays.

Upvotes: 2

Will Dean
Will Dean

Reputation: 39500

You should probably be passing frame[i] to open_input rather than &frame[i]

I also think that this:

frame = (AVFrame *) malloc(N * sizeof(AVFrame *));

should be

frame = (AVFrame **) malloc(N * sizeof(AVFrame *));

I'd have thought your compiler might be warning about that too.

If you haven't already done so, then turn up the warning level on the compiler (probably /Wall on your compiler), and deal with the results.

Upvotes: 0

Related Questions