Use strlen with scanf(%ms)

2019-07-15 13:01发布

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条回答
该账号已被封号
2楼-- · 2019-07-15 13:30

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.

查看更多
登录 后发表回答