I'm trying to write a program that dynamically increases a char
array. When I print the array, it increments the array, but old data is overwritten with whatever the user inputs and duplicates that input each time. Can someone please help me?
Desired output:
Item1
Item2
Item3
Current output:
Item3
Item3
Item3
Here is my code:
int main()
{
int length = 1;
char *list;
list = calloc(length, length * sizeof(char *));
char *temp;
char user_input[100];
while (1) {
fgets(user_input, 100, stdin);
user_input[strcspn(user_input, "\n")] = 0;
temp = realloc(list, length * sizeof(char));
strcpy(temp, user_input);
list = temp;
printf("****LIST****\n\n");
for (int item = 0; item < length; item++) {
puts(list);
}
printf("\n");
length++;
}
return 0;
}