Array Let's add a dynamically sized array to Sneklang. We'll do it in multiple parts. First, we'll just create an empty array. In later lessons, we'll make it useful.
Assignment In snekobject.h:
Add a new enum value to the snek_object_kind_t enum called ARRAY.
Create a new struct called snek_array_t that has two fields:
size – the number of elements in the array, a size_t
elements – a pointer to an array of snek object pointers, a snek_object_t **
Add a new snek_array_t field (the struct type you just created) to snek_object_data_t called v_array.
Declare the new_snek_array function.
In snekobject.c, complete the new_snek_array function. It should:
Accept a size parameter.
Allocate memory for a new pointer to a snek_object_t, and if the allocation fails return NULL.
Allocate memory for a new pointer to an array of snek objects (snek_object_t **).
How much memory should you allocate? Think about it: probably the sizeof a pointer for each element in the array. We're not storing the actual snek objects in the array, just pointers to them.
If the allocation fails, free the first snek object allocation and return NULL.
Use calloc instead of malloc so there is no "junk" in our array to start, we want beautiful, pristine NULLs. Note that calloc takes two arguments: number of objects and the size of each object.
Set the kind field to the appropriate enum.
Create a new snek_array_t struct and set the size and elements fields.
Set the v_array field of the new snek object to the newly created snek_array_t.
Return the pointer to the new snek object.