0
votes

I'm having trouble comprehending when to malloc size of a pointer vs the size of the struct. For example:

I have a struct:

 typedef struct {
   char *String;
   int Length;
 } WORD;

I want to create a pointer to an array of WORDs using pointers:

 WORD  **WordArray;
 WordArray = malloc(sizeof(WORD*))    //Since WordArray is only a single ptr to an array of WORDS

Now I need to allocate memory for each element in the array (let's say 3):

*WordArray = malloc(sizeof(WORD) * 3);  //Need to allocate the actual struct WORD * number of elements in the array

Am I allocating memory for these structs properly? If I were to ultimately free WordArray, would I need to free each individual element before I free WordArray?

1

1 Answers

0
votes

You always malloc the size of the object, and cast the result to a pointer to that.

So if you malloc a T, you cast it to a T*. And if T==WORD*, then you cast it to a WORD**. This logica works in reverse as well, if you need the cast result to be a WORD**, then the object has to be a WORD*.