So, I got to know C again, and this concept got me stuck especially.
The goal is to create a dynamically distributed array of strings. I did this by first creating a null array and allocating the appropriate amount of space for each row entered. The only problem is when I try to actually add a line, I get a seg error! I canβt understand why, I suspect that this is due to an incorrect allocation, since I do not see anything wrong with my strcpy function.
I reviewed this site in detail for an answer, and I found help, but cannot 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 ; }
source share