I'm learning C programming and I have to implement a program that read an input string of of unknown size. I wrote this code:
int main() {
char *string;
char c;
int size = 1;
string = (char*)malloc(sizeof(char));
if (string == NULL) {
printf("Error.\n");
return -1;
}
printf("Enter a string:");
while ((c = getchar()) != '\n') {
*string = c;
string = (char*)realloc(string, sizeof(char) * (size + 1));
size++;
}
string[size - 1] = '\0';
printf("Input string: %s\n", string);
free(string);
return 0;
}
But the last printf
doesn't show the whole string but only the last char.
So if I enter hello, world
the last printf
prints d
.
After a little research I tried this code and it works! But I don't get the difference with mine.
I hope I made myself clear, thank you for your attention.