Search code examples
cstringgets

Is it possible using gets without knowing the length of the array in c?


If we want to use gets in c we will do something like:

int main(void) {
  char str[100];
  while (gets(str)) {
  printf("%s\n",str); 
 }
}

We have to know the length of str first(which is 100) and then use gets. Is it possible using gets without knowing the length of the array in c?


Solution

  • If you mean using gets safely, no, it's not possible.

    Advice: don't use gets, because without knowing the length first, it may cause buffer overflow. Use fgets instead, or use gets_s in C11.

    In fact, gets has been removed from stdio.h since C11. (In C99, it's deprecated)