前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >strlen()函数和sizeof()运算符的区别

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

作者头像
lexingsen
发布2022-02-24 15:23:57
3230
发布2022-02-24 15:23:57
举报
文章被收录于专栏:乐行僧的博客乐行僧的博客

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

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

代码语言:javascript
复制
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。不保留返回值以指示错误。 参数

代码语言:javascript
复制
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运算符不能返回动态分配的数组或外部数组的大小。

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

下面用代码验证:

代码语言:javascript
复制
#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’),并不是字符串结束的标志,知道遇到结尾的空字符,才进行返回。

大家也可自行验证。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档