Search code examples
carraysreallocdynamic-allocation

Dynamic allocation of input string


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:

  1. Why does it work?
    I don't understand why, when I execute it, I can also delete characters before pressing enter. The getchar() function reads only one character at each iteration, which is written into the array, so how could I delete some ones?
    If getchar() 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.

  2. Is my code efficient? If it's not, how could I make it better (even using built-in functions)?


Solution

    1. Unless you put the terminal in "raw" mode, the operating system doesn't make input available to the application until you press return. Input editing is handled by the operating system. When you call getchar(), it reads a character from this input buffer, not directly from the terminal.

    2. There's a POSIX function getline() that does the same thing.