Вопрос

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?

Это было полезно?

Решение

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)

Другие советы

Short answer: No.

Long answer: If you know that the string will be no more than a certain size, you can always allocate a much larger chunk of memory. For example, it's unlikely that a string will be longer than 1k, so you could always simply allocate an array of size 1k. However, this is really inefficient, and also doesn't work if the strings can be arbitrarily long.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top