簡體   English   中英

與scanf(%ms)一起使用strlen

[英]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;
}

您可以在以'\\0'結尾的任何char序列上使用strlen() ,即null字符,即NUL * 1 ,實際上等於0

內存的分配方式無關緊要。

是的,這也適用於“ 動態分配 ”的內存。


* 1:不能與NULL混合使用, NULL是空指針常量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM