strlen()函数和sizeof()运算符的区别

strlen函数原型
size_t strlen(const char *string)

size_t 是无符号整数的别名,在vs2008编译器中可以查看其宏定义

typedef unsigned int size_t;

这样定义的原因一方面是字符串的长度不可能是负数,另一方面是不可能为实数。
功能
其功能是获取字符串的长度。
返回值
在MSDN文档中查看strlen函数的返回值,叙述如下。

Each of these functions returns the number of characters in string, excluding the terminal NULL. No return value is reserved to indicate an error.

每个函数都返回字符串中的字符数,不包括终端NULL。不保留返回值以指示错误。
参数

Null-terminated string

空终止字符串, 字符串标准库提供的头文件中包含操作以空字符结尾的字符串(null-terminated string)的函数。

sizeof()运算符
很对人以为sizeof是用来计算数据类型大小的一个函数,这其实是一个误区,它同加减乘除一样是运算符。

在MSDN文档查阅sizeof得到如下相关信息:
sizeof Operator
sizeof expression

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运算符
运算符表达式
sizeof关键字提供了与变量或类型(包括聚合类型)相关的存储空间。该关键字返回类型size_t的值。
表达式要么是标识符,要么是类型转换表达式(括号中包含的类型说明符)。
当应用到结构类型或变量时,sizeof返回实际大小,其中可能包括插入用于对齐的填充字节。当应用到静态尺寸数组时,sizeof返回整个数组的大小。sizeof运算符不能返回动态分配的数组或外部数组的大小。

了解了以上的相关知识,我们可以总结出两者不同。

下面用代码验证:

#include<stdio.h>
#include <string.h>
void main()
{
    char str1[10] = {'h','e',0,'l','l','o'};
    char str2[10] = "he0llo";

    printf("%d\n",sizeof(str1)); //6   10
    printf("%d\n",sizeof(str2)); //10
    printf("%d\n",strlen(str1)); //6    2
    printf("%d\n",strlen(str2)); //6

}

执行代码得到的结果如下:
这里写图片描述
分析上图得到的结果,定义两个长度为10个字节的字符数组,由上文可知,sizeof()运算符是计算整个数组的大小,所以输出均为10

而经过strlen计算字符串长度,由其函数特性,在str1数组中,当遇到第一个数字0是strlen函数就已经结束。所以输出的结果为2.
在str2数组中,在字符串中有0的存在,但实际上这时的0为字符字符0(‘0’),并不是字符串结束的标志,知道遇到结尾的空字符,才进行返回。

大家也可自行验证。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值