设为首页 加入收藏

TOP

C语言的sizeof和strlen
2013-04-10 10:08:01 来源: 作者: 【 】 浏览:357
Tags:语言 sizeof strlen

  strlen是函数,而sizeof是算符。strlen需要进行一次函数调用,而对于sizeof而言,因为缓冲区已经用已知字符串进行了初始化,起长度是固定的,所以sizeof在编译时计算缓冲区的长度。

  因为sizeof()测试的是数组的长度。而strlen测试的是字符串的长度。在定义数组时,字符串后面还有一个结束标志'\0',这个也要算进去!

  [cpp] view plaincopyprint

  #include <stdio.h>

  #include <string.h>

  main()

  {

  char ss[]="string";

  printf("%d %d \n",sizeof(ss),strlen(ss));

  }

  #include <stdio.h>

  #include <string.h>

  main()

  {

  char ss[]="string";

  printf("%d %d \n",sizeof(ss),strlen(ss));

  }


  代码修改下:

  [cpp] view plaincopyprint

  #include <stdio.h>

  #include <string.h>

  main()

  {

  char ss[]="string";

  ss[0]=0;

  ss ='\0';

  ss ='0';

  printf("%d %d \n",sizeof(ss),strlen(ss));

  }

  #include <stdio.h>

  #include <string.h>

  main()

  {

  char ss[]="string";

  ss[0]=0;

  ss ='\0';

  ss ='0';

  printf("%d %d \n",sizeof(ss),strlen(ss));

  }


  声明x的时候x里面存储的是"string\0",最后的\0是结束符,所以sizeof(x)就是7.
  而\0的asccii码值为0,strlen(x)是计算到\0位置,strlen(x)也就是0了。
  注意:=0和='\0'都是结束。而='0'是真正的给对应位置置为字符0
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言实现合并排序 下一篇C语言 malloc 工作机制

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: