strlen && sizeof 计算字符串长度的区别

记录一个之前没有遇到的知识点:

区别 1. strlen && sizeof:strlen在计算字符串长度时不包含'\0'空字符;sizeof包含空字符

区别 2. 字符串作为指针传入函数:函数内部调用sizeof计算传入字符串长度不可行,此时获取的为变量地址的长度永远是8个字节(4个字节如果是32位系统); 但strlen不受影响,无论在函数内部和外部;

新增:区别 3.当创建一个固定长度数组接收一个不定长字符串时。使用sizeof计算的永远时数组创建的大小。如下面例子:example[10] 永远时10个char大小。但是strlen 会计算‘\0’作为结尾实际字符串的大小。

#include <stdio.h>
#include <string.h>
void example(char*string)
{
	int size=sizeof(string);
	int str_len=strlen(string);
	printf("the sizeof inside function: %d\n",size);
	printf("the strlen inside function: %d\n",str_len);
	
}

int main()
{
//example 1 & 2
	char a[]="123456789";
	int size=sizeof(a);
	int str_lenth=strlen(a);
    printf("the sizeof outside of function %d\n",size);
	printf("the strlen outside of function %d\n",str_lenth);
	example(a);
//example 3
	char example[10]="1";
	int strlen_example = strlen(example);
	int sizeof_example = sizeof(example);
    printf("strlenth of array[10]: %d \n",strlen_example);
	printf("sizeof of array[10]: %d \n",sizeof_example);

   return 0;
}
the sizeof outside of function 10
the strlen outside of function 9
the sizeof inside function: 8
the strlen inside function: 9
strlen of array[10]: 1 
sizeof of array[10]: 10 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值