C语言的sizeof和strlen

strlen是函数,而sizeof是算符。strlen需要进行一次函数调用,而对于sizeof而言,因为缓冲区已经用已知字符串进行了初始化,其长度是固定的,所以sizeof在编译时计算缓冲区的长度。strlen是遇到0或者'\0'都会停止运算的,而sizeof是每个字符都会算的,不会漏掉0(或者'\0')

 

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

#include "stdafx.h"
#include <iostream>
#include <string>
#include <string.h> 
using namespace std;

int main()  
{  
	char ss[]="string";  
	//sizeof是计算全字符的,包括'\0',strlen是没有计算最后一个结束符的,strlen遇到0就停止
	printf("%d %d \n",sizeof(ss),strlen(ss));//输出7 和 6

	system("pause");
	return 0;

} 


代码修改下:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <string.h> 
using namespace std;

int main()  
{  
	char ss[]="string";  
	ss[0]=0;  
	ss[1]='\0';  
	ss[2]='0';  
	printf("%d %d \n",sizeof(ss),strlen(ss)); //strlen遇到0和'\0'都会停止运算的

	system("pause");
	return 0;

}  


声明x的时候x里面存储的是"string\0",最后的\0是结束符,所以sizeof(x)就是7。
而\0的asccii码值为0,strlen(x)是计算到\0位置,strlen(x)也就是0了。
注意:=0和='\0'都是结束。而='0'是真正的给对应位置置为字符0


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值