groove
groove

Reputation: 283

Dynamic Array of Structures

I have a few questions about a piece of code that I have found on web, which is located at http://www.c.happycodings.com/Data_Structures/code9.html.

  1. Why is strarray defined as **?
  2. Do we have to first malloc() the array, and then malloc() each element of it?

    strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

    strarray[count] = (struct node *)malloc(sizeof(struct node));

  3. How to free() this array totally?

Thanks

Upvotes: 0

Views: 502

Answers (2)

Minion91
Minion91

Reputation: 1929

  1. The strarray is a pointer to an array of pointers with each pointer pointing to a node struct. This is the basic representation of an array of objects. For basic types you can use only one *, because it's a pointer to an array of basic types. You can do that for structs too, it just depends on what you want to do with the array.

  2. Yes, yes you do.

  3. First iterate over the array, freeing every member, then free the array. The clue to freeing: free everything you have allocated.

Upvotes: 2

AusCBloke
AusCBloke

Reputation: 18492

  1. strarray is of type struct node ** because it's a dynamically allocated array of struct node * - ie. an array of pointers, where each element points to a struct node.

  2. No, depending on what you're trying to achieve you could simply allocate a block of memory to hold X struct node, and assign that pointer to a struct node *. The person who wrote that code allocated memory for an array of pointers, which is why they then made a call to malloc to allocate memory for each individual struct node.

    A possibility for them using a dynamic array of pointers to dynamically allocated struct node, as opposed to simply allocating a single block of contiguous struct node could have to do with lessening the cost of (if required) copying the whole array when calling realloc.

  3. To free the memory, you do things in reverse. Free each element in the array, and then free the entire array.

Upvotes: 1

Related Questions