This is pretty quick and dirty, but something like this.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define INITIAL_STRING_SIZE 10
#define INITIAL_STRING_ARRAY_SIZE 10
char* GetString ();
char** StoreStrings (int *size);
void DeleteStrings (char ***strings, int size);
void* realloc_or_free (void *in, size_t sz);
void die (const char *msg);
int main() {
char **strings = NULL;
int size, i;
strings = StoreStrings(&size);
for (i = 0; i < size; i++)
printf("%s\n", strings[i]);
DeleteStrings(&strings, size);
return 0;
}
char *GetString() {
int c, size = 0, allocated = INITIAL_STRING_SIZE;
char *str;
str = malloc(allocated);
if (str == NULL)
return NULL;
while ((c = getchar()) != EOF && c != '\n') {
if (size == allocated - 1) {
str = realloc_or_free(str, allocated *= 2);
if (str == NULL)
return NULL;
}
str[size++] = c;
}
str[size] = '\0';
/* Fit to size and return. */
return realloc_or_free(str, size + 1);
}
char **StoreStrings(int *size) {
int allocated = INITIAL_STRING_ARRAY_SIZE;
char **strings, **temp;
*size = 0;
strings = malloc(allocated * sizeof(char*));
if (strings == NULL)
die("StoreStrings 1");
printf("Enter strings. Enter an empty string to quit.\n");
while (1) {
char *str = GetString();
if (str == NULL) {
DeleteStrings(&strings, *size);
die("StoreStrings 2");
}
if (str[0] == '\0') {
free(str);
break;
}
if (*size == allocated) {
temp = realloc(strings, (allocated *= 2) * sizeof(char*));
if (temp == NULL) {
DeleteStrings(&strings, *size);
die("StoreStrings 3");
}
strings = temp;
}
strings[(*size)++] = str;
}
/* Fit to size. */
temp = realloc(strings, *size * sizeof(char*));
if (temp == NULL) {
DeleteStrings(&strings, *size);
die("StoreStrings 4");
}
return temp;
}
void DeleteStrings(char ***strings, int size) {
int i;
for (i = 0; i < size; i++)
free((*strings)[i]);
free(*strings);
*strings = NULL;
}
/* Frees original storage if realloc fails. */
void *realloc_or_free(void *in, size_t sz) {
void *p;
p = realloc(in, sz);
if (p == NULL)
free(in);
return p;
}
/* Print error message and exit. */
void die(const char *msg) {
fprintf(stderr, "Error: %s\n", msg);
exit(EXIT_FAILURE);
}