将 strlen 与 scanf(%ms) 结合使用
Use strlen with scanf(%ms)
是否可以在动态分配的字符串上使用 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;
}
您可以在以 '[=12=]'
结尾的任何 char
序列上使用 strlen()
,空字符又名 NUL
*1,实际上等于 0
.
内存的分配方式无关紧要。
所以是的,这也适用于“动态分配”内存。
*1:不能和空指针常量NULL
混淆。
是否可以在动态分配的字符串上使用 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;
}
您可以在以 '[=12=]'
结尾的任何 char
序列上使用 strlen()
,空字符又名 NUL
*1,实际上等于 0
.
内存的分配方式无关紧要。
所以是的,这也适用于“动态分配”内存。
*1:不能和空指针常量NULL
混淆。