change the way string arrays are initialized

This commit is contained in:
Chris Cromer 2021-07-16 13:35:29 -04:00
parent 1b68196f16
commit e548acdb8a
3 changed files with 25 additions and 27 deletions

View File

@ -19,11 +19,13 @@
/**
* Create a String Array by initializing its structure.
* @param string_array The String Array to create.
* @return Returns a new String Array.
*/
void create_string_array(StringArray *string_array) {
StringArray *create_string_array() {
StringArray *string_array = malloc(sizeof(StringArray));
string_array->array = NULL;
string_array->size = 0;
return string_array;
}
/**
@ -93,22 +95,19 @@ void delete_string_array(StringArray *string_array, int index) {
* @param string_array The String Array to free.
*/
void free_string_array(StringArray *string_array) {
if (string_array->array == NULL) {
fprintf(stderr, "StringArray is not freeable!\n");
free_string_array(string_array);
exit(EXIT_FAILURE);
for (size_t i = 0; i < string_array->size; i++) {
if (string_array->array[i] != NULL) {
free(string_array->array[i]);
string_array->array[i] = NULL;
}
}
else {
for (size_t i = 0; i < string_array->size; i++) {
if (string_array->array[i] != NULL) {
free(string_array->array[i]);
string_array->array[i] = NULL;
}
}
if (string_array->array != NULL) {
free(string_array->array);
string_array->array = NULL;
}
string_array->size = 0;
if (string_array->array != NULL) {
free(string_array->array);
string_array->array = NULL;
}
string_array->size = 0;
if (string_array != NULL) {
free(string_array);
string_array = NULL;
}
}

View File

@ -27,7 +27,7 @@ typedef struct {
size_t size;
} CleanArray;
void create_string_array(StringArray *string_array);
StringArray *create_string_array();
void insert_string_array(StringArray *string_array, char *string);

View File

@ -64,13 +64,12 @@ void loop() {
char *line = get_console_input();
StringArray args;
create_string_array(&args);
StringArray *args = create_string_array();
char *saveptr = NULL;
char *token = strtok_r(line, " ", &saveptr);
while (token) {
insert_string_array(&args, token);
insert_string_array(args, token);
token = strtok_r(NULL, " ", &saveptr);
}
if (line != NULL) {
@ -79,17 +78,17 @@ void loop() {
}
// The user didn't type anything so restart the loop
if (args.size == 0) {
if (args->size == 0) {
continue;
}
if (is_builtin(args.array[0])) {
run_builtin(&args);
if (is_builtin(args->array[0])) {
run_builtin(args);
}
else {
launch_program(&args);
launch_program(args);
}
free_string_array(&args);
free_string_array(args);
}
}