Is it possible using gets without knowing the leng

2020-05-09 22:35发布

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?

标签: c string gets
2条回答
贼婆χ
2楼-- · 2020-05-09 23:21

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)

查看更多
叼着烟拽天下
3楼-- · 2020-05-09 23:33

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.

查看更多
登录 后发表回答