Last active
September 15, 2020 18:36
-
-
Save cs-fedy/dcf3a7bdf3aba7a5b8fe561b10768723 to your computer and use it in GitHub Desktop.
dynamic array implementation using C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
Arr * create_arr(int max_size) { | |
Arr * new_arr = malloc(sizeof(Arr)); | |
new_arr -> size = 0; | |
new_arr -> max_size = 0; | |
new_arr -> items = malloc(max_size * sizeof(int)); | |
if (new_arr -> items != NULL) { | |
new_arr -> max_size = max_size; | |
} | |
return new_arr; | |
} | |
void allocate_new_memory_case(Arr * arr) { | |
int * tmp_arr = NULL; | |
arr -> max_size++; | |
// fix realloc: invalid next size. | |
tmp_arr = realloc(arr -> items, sizeof(int) * arr -> max_size); | |
if (tmp_arr != NULL) { | |
arr -> items = tmp_arr; | |
} else { | |
perror("Error while reallocating arr -> items!!"); | |
exit(EXIT_FAILURE); | |
} | |
} | |
void append(int key, Arr * arr) { | |
if (arr -> items == NULL) { | |
perror("arr -> items is NULL!!"); | |
exit(EXIT_FAILURE); | |
} | |
if (arr -> size > arr -> max_size) { | |
allocate_new_memory_case(arr); | |
} | |
arr -> items[arr -> size++] = key; | |
} | |
void destroy_arr(Arr * arr) { | |
free(arr -> items); | |
free(arr); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Arr{ | |
int * items; | |
int size; | |
int max_size; | |
}; | |
typedef struct Arr Arr; | |
Arr * create_arr(int max_size); | |
void allocate_new_memory_case(Arr * arr); | |
void append(int key, Arr * arr); | |
void destroy_arr(Arr * arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment