Skip to content
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions arrays/arrays.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ typedef struct Array {
*****/
Array *create_array (int capacity) {
// Allocate memory for the Array struct

Array *newArray = malloc(sizeof(Array));
// Set initial values for capacity and count

newArray->capacity = capacity;
newArray->count = 0;
// Allocate memory for elements

newArray->elements = calloc(capacity, sizeof(char *));
return newArray;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very well done!

}


Expand All @@ -35,9 +37,14 @@ Array *create_array (int capacity) {
void destroy_array(Array *arr) {

// Free all elements

for (int i = 0; i < arr->count; i++)
{
arr->elements[i] = NULL;
free(arr->elements[i]);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be the proper way of freeing everything.

// Free array

free(arr->elements);
free(arr);
}

/*****
Expand All @@ -47,13 +54,26 @@ void destroy_array(Array *arr) {
void resize_array(Array *arr) {

// Create a new element storage with double capacity
char **newElements = calloc((2 * arr->capacity), sizeof(char *));

// Copy elements into the new storage
for (int i = 0; i < arr->count; i++)
{
newElements[i] = arr->elements[i];
}

// Free the old elements array (but NOT the strings they point to)

// Update the elements and capacity to new values
for (int i = 0; i < arr->count; i++)
{
arr->elements[i] = NULL;
free(arr->elements[i]);
}
free(arr->elements);

// Update the elements and capacity to new values
arr->elements = newElements;
arr->capacity = arr->capacity * 2;
}


Expand Down