代码示例1:mesg[ ] = " "

#include <stdio.h>
#include <string.h>
 
int main()
{
    char mesg[] = "";
    
    printf("strlen of mesg:%d\n",(int)strlen(mesg));
    
    printf("sizeof mesg:%d\n",(int)sizeof(mesg)/(int)sizeof(char));
 
    return 0;
}

测试结果:

xuanmiao@linux:~/demo/test$ ./test 
strlen of mesg:0
sizeof mesg:1
  • strlen 计算的是字符串的有效长度(不包括终止符 \0)。

  • sizeof 计算的是数组的总大小(包括所有字符和终止符 \0)。

  • mesg 的实际内容是 {'\0'},因此 strlen 返回 0sizeof 返回 1

 

代码示例2:mesg[ ] = "\0"

#include <stdio.h>
#include <string.h>
 
int main()
{
    char mesg[] = "\0";
    printf("strlen of mesg:%d\n",(int)strlen(mesg));
    printf("sizeof mesg:%d\n",(int)sizeof(mesg)/(int)sizeof(char));
    return 0;
}

 

测试结果

xuanmiao@linux:~/demo/test$ gcc test.c -o test
xuanmiao@linux:~/demo/test$ ./test 
strlen of mesg:0
sizeof mesg:2
  • mesg 的实际内容是 {'\0', '\0'},因此 strlen 返回 0sizeof 返回 2

posted on 2022-11-10 13:52  轩~邈  阅读(39)  评论(0)    收藏  举报