Skip to content

Instantly share code, notes, and snippets.

@LiquidFenrir
Created July 14, 2018 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LiquidFenrir/f3053490d9caf0f971686e658771f3f5 to your computer and use it in GitHub Desktop.
Save LiquidFenrir/f3053490d9caf0f971686e658771f3f5 to your computer and use it in GitHub Desktop.
string_append
#include <stdio.h>
#include <stdlib.h>
// You need to pass a pointer since the pointer itself is being modified
void append_string(const char *** array, const char * string)
{
if(*array == NULL) // If the array is empty, allocate it with size 2 for the current string and an ending null marker
{
*array = malloc(sizeof(const char *)*2);
if(*array == NULL) // if *array is NULL, then malloc failed because it couldn't find enough memory
{
printf("Failed to malloc!\n");
return;
}
else
{
(*array)[0] = string;
(*array)[1] = NULL; // the null marker allows it to find the size: just go over the array until you find it
}
}
else // If the array isn't empty, search for the null marker to find the size and reallocate it bigger
{
size_t size = 0;
while((*array)[size] != NULL) // search for the null marker, and stop once we found it
{
size++;
}
const char ** new_array = realloc(*array, sizeof(const char *)*(size+2)); // size only counts the number of strings already in the array, so you need +1 for the null marker, and +1 for new null marker
if(new_array == NULL) // if new_array is NULL, then realloc failed because it couldn't find enough memory
{
printf("Failed to realloc!\n");
return;
}
else
{
*array = new_array;
(*array)[size] = string; // add the new string right before the end, over the null marker
(*array)[size+1] = NULL; // and a new null marker at the end
}
}
}
int main()
{
const char ** array = NULL; // starts as NULL so the function knows it's empty
append_string(&array, "HELLO"); // pass a pointer to the array so the NULL can get changed into something else
append_string(&array, "WORLD");
append_string(&array, "!!!");
for(int i = 0; array[i] != NULL; i++)
{
printf("String %d in array is: %s\n", i+1, array[i]);
}
free(array); // don't forget to free, or else you leak memory!
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment