diff options
Diffstat (limited to 'src/strarray.c')
-rw-r--r-- | src/strarray.c | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/src/strarray.c b/src/strarray.c new file mode 100644 index 0000000..12ddbf8 --- /dev/null +++ b/src/strarray.c @@ -0,0 +1,78 @@ +// GPGEdit edits GPG encrypted files +// Copyright (C) 2018 Aaron Ball <nullspoon@oper.io> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. +#include "strarray.h" + + +// strarray_new: +// Pretty much useless constructor. Here mostly for consistency. This can +// easily be replaced with your own malloc statement provided index 0 is set to +// NULL. +// +// NOTE: If not using this, initialized memory *must* be allocated in the heap, +// as growing the string array requires reallocating the memory, which +// can't be done in the stack. +char** strarray_new() { + char** out = malloc(sizeof(char*)); + out[0] = NULL; + return out; +} + + +// strarray_add: +// Dynamically grows a string array (pointer to char array containing pointers +// to char arrays - sorry). Reallocates storage for the original array plus +// room for one additional pointer. Once data is copied in, the source array +// pointer is updated to point to the new storage. +// +// @strorig Source string array pointer +// @newstr New string to add to the string array. +void strarray_add(char*** strorig, char* newstr) { + int i = 0; + char** newstrarr; + + // Count the number of existing strings + while(*strorig[i] != NULL) + i++; + + // Reallocate old array + 1 + newstrarr = (char**) realloc(*strorig, sizeof(char*) * (i + 1)); + + // Append new string to the array + newstrarr[i] = malloc(strlen(newstr) + 1); + strcpy(newstrarr[i], newstr); + // Don't forget the null terminator! + newstrarr[i + 1] = NULL; + + // Repoint strorig to newstrarr memory + *strorig = newstrarr; +} + + +// strarray_release: +// Destructor for a string array. Frees each item in the array before freeing +// the array itself. +// +// @strarray Array to free +void strarray_release(char*** strarray) { + int i = 0; + + while(*strarray[i] != NULL) { + free(*strarray[i]); + i++; + } + free(*strarray); +} + |