问题
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 char
s 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