I'm trying to take an unknown amount of lines of console input, convert each line to a String using malloc, and then add each string to an array of strings by dynamically reallocating memory each time. My goal is to have an array where each element is a different line entered by the console (the while loop should end with EOF).
My code is below.
char * inputString = (char *)malloc(100);
char * aWord = (char *)malloc(1);
char ** listWords = (char **)malloc(1);
int wordCount = 0;
while (fgets(inputString, 100, stdin) != NULL)
{
wordCount++;
*(inputString + (strlen(inputString) - 1)) = '\0';
aWord = (char *)realloc(aWord, strlen(inputString) + 1);
aWord = inputString;
listWords = realloc(listWords, sizeof(char) * wordCount);
*(listWords + (wordCount - 1)) = aWord;
}
for (int i = 0; i < wordCount; i++)
printf("%s\n", listWords[i]);
If I were to input in console
abc\n
b\n
cad\n
^Z\n
In theory, I would like my code to print out
abc\n
b\n
cad\n
Each line of console input. Instead it prints
cad\n
cad\n
cad\n
The last line entered. Help much appreciated