与scanf(%ms)一起使用strlen [英] Use strlen with scanf(%ms)
本文介绍了与scanf(%ms)一起使用strlen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在动态分配的字符串上使用 strlen()
?
Is it possible to use strlen()
over a dynamically allocated string?
举例:
#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;
}
推荐答案
您可以使用 strlen()
在任何以'\0'$ c结尾的
char
序列上$ c>,也就是 NUL
* 1 的空字符,实际上等于 0
。
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:不与 NULL
,它是空指针常量。
*1: Not be mixed up with NULL
, which is the null-pointer constant.
这篇关于与scanf(%ms)一起使用strlen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文