I've written the following function to dynamically allocate an input string while typing, without asking the user how many characters it's long.
#include<stdio.h>
#include<stdlib.h>
char* dyninp (char str[], int *n) {
char ch;
int i = 0;
do {
ch = getchar();
str = (char *) realloc(str, (i+1)*sizeof(char));
str[i] = ch;
i++;
} while (ch != '\n');
/*substitute '\n' with '\0'*/
str[i-1] = '\0';
if (n != NULL) {
/*i contains the total lenght, including '\0'*/
*n = i-1;
}
/*because realloc changes array's address*/
return str;
}
/*it is called in this way:
char *a;
int n;
a = dyninp (a, &n);
*/
This code works, but I have some questions about it:
Why does it work?
I don't understand why, when I execute it, I can also delete characters before pressing enter. Thegetchar()
function reads only one character at each iteration, which is written into the array, so how could I delete some ones?
Ifgetchar()
deletes the previous character when receives '\127', then the loop should continue executing as with any other character. But this doesn't happen, because, when loop ends, "i" always contains the exact number of elements.Is my code efficient? If it's not, how could I make it better (even using built-in functions)?