0

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?

1
  • Why an array of pointers instead of an array of structs? Commented Nov 12, 2015 at 21:26

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

This doesn't answer OP's question.
The question was "how should I free the memory", not "should I free the memory".
Then use the free() function, its parameter is the pointer to a memory block previously allocated with malloc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.