Skip to content

Instantly share code, notes, and snippets.

@TNick
Created March 5, 2014 10:13
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 TNick/9364630 to your computer and use it in GitHub Desktop.
Save TNick/9364630 to your computer and use it in GitHub Desktop.
A simple dynamic array in c
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int allocated_size = 10;
int used_size = 0;
char c, *input, *tmp_input;
// allocate our buffer
input = (char*)malloc(allocated_size);
if (input == NULL) {
printf("Memory allocation error");
return 1;
}
printf("Input a string, press enter when done: ");
while((c = getchar()) != '\n') {
// make sure there's an empty one at the end to avoid
// having to do this check after the loop
if (used_size == allocated_size-1) {
// see http://stackoverflow.com/questions/19146037/efficiency-of-growing-a-dynamic-array-by-a-fixed-constant-each-time
allocated_size *= 2;
tmp_input = (char*)realloc(input, allocated_size);
if (tmp_input == NULL) {
free (input);
printf("Memory allocation error");
return 1;
}
input = tmp_input;
}
input[used_size++] = c;
}
// we are sure that there's a spot for last one
// because of if (used_size == allocated_size-1)
input[used_size] = '\0';
printf("\nYou entered the string: %s\n", input);
// free our buffer
free (input);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment