【零碎知识点】超详解strlen与sizeof区别

4.1 sizeof

The sizeof keyword gives the amount(数量,程度) of storage, in bytes, associated(联系相关) with a variable or a type (including aggregate(总计的) types). This keyword returns a value of type size_t.

The expression is either an identifier or a type-cast expression (a type specifier enclosed in parentheses).

When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.

sizeof关键字给出了与变量或类型(包括聚合类型)相关联的存储容量(以字节为单位)。这个关键字返回size_t类型的值。

表达式要么是标识符,要么是类型转换表达式(用圆括号括起来的类型说明符)。

当应用于结构类型或变量时,sizeof返回实际大小,其中可能包括为对齐而插入的填充字节。当应用于静态维度数组时,sizeof返回整个数组的大小。sizeof操作符不能返回动态分配的数组或外部数组的大小。

sizeof是关键字是c语言中的操作符,计算的是所传入数据所占空间大小也就是字节数

#include<stdio.h>
int main()
{
	char a[] = "abcde";
	char a1[] = "a,b,c,d,e";
	char a2[] = { 'a','b','c','d','e' };
	printf("%d\n", sizeof(a));		//6
	printf("%d\n", sizeof(a[0]));	//1
	printf("%d\n", sizeof(a1));		//10
	printf("%d\n", sizeof(a1[0]));	//1
	printf("%d\n", sizeof(a2));		//5
	printf("%d\n", sizeof(a2[0]));	//1

	printf("%d\n", strlen(a));		//5
	printf("%d\n", strlen(a1));  	//9
	printf("%d\n", strlen(a2));		//随机值
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ab8AvRAR-1646539183178)(watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAWkJsYWNrIHZpdGFsaXR5,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center-16465390857493.png)]

4.2strlen

Each of these functions returns the number of characters in string, not including the terminating null character.

strlen是函数返回的是字符串中的字符数不包含结束的空字符(以\0作为计算结束的重点)

4.3易错点:sizeof在自定义函数中使用

#include<stdio.h>
void myStrlen1(char* a)
{
	int sum=0;
	int sz = sizeof(a) / sizeof(a[0]);
	printf("%d\n", sizeof(a) / sizeof(a[0]));
    //运算出来是4因为此时a为指针所占空间为4或者8
	for (int i = 0; i < sz+1; i++)
	{
		if (a[i] != '\0')
			sum++;
	}
	printf("%d\n", sum);
}
int myStrlen2(char* a)
{
	if (*a != '\0')
	{
		return 1 + myStrlen2(a + 1);
	}
	else
		return 0;
}
int main()
{
	char a[] =  "abcde";
	myStrlen1(a);
	printf("%d\n",myStrlen2(a));
	printf("%d\n", sizeof(a));
	printf("%d\n", sizeof(a[0]));
	printf("%d\n", sizeof(a) / sizeof(a[0]));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值