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

天大地大妈咪最大 提交于 2019-12-02 23:17:34

问题


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?


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/17737078/is-it-possible-using-gets-without-knowing-the-length-of-the-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!