How to add string to array of strings in C

colinmcp picture colinmcp · Jan 11, 2015 · Viewed 18.4k times · Source

So I am getting re-acquainted with C, and this one concept has me particularly stuck.

The goal is to create a dynamically allocated array of strings. I have this done, first creating a null array and allocating the appropriate amount of space for each string entered. The only problem is, when I try to actually add a string, I get a seg fault! I can't figure out why, I have a hunch that it is from improper allocation as I can't see anything wrong with my strcpy function.

I have looked exhaustively on this site for an answer, and I have found help, but can't quite close the deal. Any help you can provide would be greatly appreciated!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  int count = 0; //array index counter
  char *word; //current word
  char **array = NULL;


  char *term = "q"; //termination character
  char *prnt = "print";

  while (strcmp(term, word) != 0)
{
  printf("Enter a string.  Enter q to end.  Enter print to print array\n");
  // fgets(word, sizeof(word), stdin); adds a newline character to the word.  wont work in this case
  scanf("%s", word);

  //printf("word: %s\nterm: %s\n",word, term);

  if (strcmp(term, word) == 0)
    {
    printf("Terminate\n");
    } 

  else if (strcmp(prnt, word) == 0)
  {
    printf("Enumerate\n");

    int i;

    for (i=0; i<count; i++)
    {
      printf("Slot %d: %s\n",i, array[i]);
    }

  }
  else
  {
    printf("String added to array\n");
    count++;
    array = (char**)realloc(array, (count+1)*sizeof(*array));
    array[count-1] = (char*)malloc(sizeof(word));
    strcpy(array[count-1], word);
  }

}

  return ;

}

Answer

Danny Daglas picture Danny Daglas · Jan 11, 2015

word has no memory allocated to it. Your program in its current form is trampling over unallocated memory as users enter words into your program.

You should guesstimate how large your input would be and allocate the input buffer like this:

char word[80];  // for 80 char max input per entry