Mat*_*hio 2 c scanf c-strings strlen dynamic-memory-allocation
是否可以使用strlen()
动态分配的字符串?
例如:
#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;
}
Run Code Online (Sandbox Code Playgroud)
你可以使用strlen()
任何以char
s结尾的s 序列'\0'
,即空字符aka NUL
*1,实际上等于0
.
如何分配内存并不重要.
所以是的,这也适用于" 动态分配 "的内存.
*1:不与之混淆NULL
,这是空指针常量.