strlen与sizeof的区别

8 篇文章 0 订阅

strlen


头文件:string.h
定义:size_t strlen ( const char * str );
功能:get string length。

1.The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
也即是,该strlen函数返回字符串的长度(从字符串的开始至null之前的长度),例如strlen(“Hello”)的返回值为5.
2.This should not be confused with the size of the array that holds the string. For example:

char mystr[100]="test string";

efines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.
也即是,对于已经初始化的数组长度为实际的字符串长度。



sizeof


头文件:stdio.h
功能: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.
其返回值类型为size_t,在头文件stddef.h中定义。这是一个依赖于编译系统的值,
一般定义为:

typedef unsigned int size_t;


strlen与sizeof的区别


1、strlen()函数求的是字符串的实际长度,直到遇到第一个’\0’,然后就返回计数值,且不包括’\0’。
而sizeof()函数返回的是变量声明后所占的内存数,不是实际长度。
例如:

char input[256]="hello";
strlen(input);//5
sizeof(input);//256

2、sizeof操作符的结果类型是size_t,它在头文件中typedef为unsigned int类型。
该类型保证能容纳实现所建立的最大对象的字节大小。
3、sizeof是算符,strlen是函数。
4、sizeof可以用类型做参数,strlen只能用char*做参数,且必须是以”\0”结尾的。但sizeof还可以用函数做参数。



参考示例


示例1:

char a[] = "hello world";
char *p = a;
cout<< sizeof(a) << endl; // 12 字节
cout<< sizeof(p) << endl; // 4 字节


其中,sizeof(a)的值是12(注意别忘了’\0’)。指针p 指向a,但是sizeof(p)的值却是4。这是因为sizeof(p)得到的是一个指针变量的字节数,相当于sizeof(char*),而不是p 所指的内存容量。
C++/C 语言没有办法知道指针所指的内存容量,除非在申请内存时记住它。


示例2:

void Func(char a[100])
{
    cout<< sizeof(a) << endl; // 4 字节而不是100 字节
}

注意当数组作为函数的参数进行传递时,该数组自动退化为同类型的指针。
示例2中,不论数组a 的容量是多少,sizeof(a)始终等于sizeof(char *)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值