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;
}
You can use
strlen()
on any sequence ofchar
s ended by a'\0'
, the null-character akaNUL
*1, which in fact equals0
.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.