Use strlen with scanf(%ms)

泄露秘密 提交于 2019-12-11 01:42:36

问题


Is it possible to use strlen() over a dynamically allocated string?

FOR EXAMPLE:

#include <stdio.h>
#include <string.h>

int main ()
{
  char *input=NULL;
  printf ("Enter a sentence: ");
  scanf("%ms", &input);
  //Is this legit?
  printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(input));
  return 0;
}

回答1:


You can use strlen() on any sequence of chars ended by a '\0' , the null-character aka NUL*1, which in fact equals 0.

It does not matter how the memory has been allocated.

So yes, this also applies to "dynamically allocated" memory.


*1: Not be mixed up with NULL, which is the null-pointer constant.



来源:https://stackoverflow.com/questions/51693473/use-strlen-with-scanfms

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