Suzy Tros
Suzy Tros

Reputation: 373

how to allocate memory for array of pointers to struct and then free it?

I want to allocate space for an array of pointers to structs so here is what I did.

typedef struct A_example{
  struct B_example* B_array[MAX_SIZE];
} A
typedef struct B_example{
  int a;
}B
A A_array[MAX_SIZE2];

so to allocate memory for B_Array for an element of A_array I do this:

A_array[current_element].B_array[i] = (struct B_example*)malloc(sizeof(struct B_example)); 

is this correct? and how should I free the memory for this?

Upvotes: 0

Views: 59

Answers (2)

Tony Tannous
Tony Tannous

Reputation: 473

Yes, if you don't want to have a memory leak.

Upvotes: 0

R_Kapp
R_Kapp

Reputation: 2858

Your allocation appears to be correct (aside from the standard advice that is normally given to not cast the return of malloc). You can free it via free(A_array[current_element].B_array[i]);.

Upvotes: 2

Related Questions