sizeof()与strlen()的区别与联系

本文详细解析了C语言中sizeof与strlen的功能差异。sizeof是操作符,用于获取变量或类型的字节存储大小;而strlen是函数,用于计算字符串的实际长度,不包括终止符。此外,介绍了两者在编译和运行时的不同表现。

从外部特性来看:

#include <stdio.h> #include <string> int main() { char array[] = "12345"; int n = sizeof(array); // n is 6 int m = strlen(array); // m is 5 array[3] = 0; n = sizeof(array); // n is 6 m = strlen(array); // m is 3 return 0; }


 

两者最本质的区别在于sizeof是操作符,而strlen是函数。

他们在MSDN中的定义分别为:

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.

 -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

strlen

 

Get the length of a string.

 

Routine Required Header:

strlen <string.h>

 

size_t strlen( const char *string );

Parameter

string:Null-terminated string

Libraries

All versions of the C run-time libraries.

 

Return Value

Each of these functions returns the number of characters in string, excluding the terminal

NULL. No return value is reserved to indicate an error.

 

Remarks

Each of these functions returns the number of characters in string, not including the

terminating null character. wcslen is a wide-character version of strlen; the argument of

wcslen is a wide-character string. wcslen and strlen behave identically otherwise.

 

可见strlen是针对string的,而sizeof仅仅是一个keyword.

大部分编译器在编译时就计算了sizeof的值,而strlen则是在程序执行过程中计算的。

sizeof计算出的是该类型所占内存的大小,而strlen计算出的则是字符串的实际长度。

 

Evaluating sizeof expr does not evaluate the expression.

The result of applying sizeof depends in part on the type involved:

l  sizeof char or an expression of type char is guaranteed to be 1

l  sizeof a reference type returns the size of the memory necessary to contain an object of the referenced type

l  sizeof a pointer returns the size needed hold a pointer; to obtain the size of the object to which the pointer pointers, the pointer must be dereferenced

l  sizeof an array is equivalent to taking the sizeof the element type times the number of elements in the array

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值