1

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)?

2 Answers 2

1
  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.

Sign up to request clarification or add additional context in comments.

Comments

1

Answer for the first question:

The reason for this is probably buffering in the terminal driver. A short explanation is provided here in the notes section. The getchar() function does not receive any input until a line has been committed by the user in the terminal when it receives the whole string and returns it character by character. Deletion is therefore a feature of your terminal, not your program.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.