sizeof 与 strlen 不同

一、MSDN定义
1、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 keywordreturns a value of type size_t.

 

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

 

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

大体意思就是说:

1、sizeof是运算符

2、返回值类型为size_t(unsignedint),字节数

3、参数为一个变量或一个类型(结构体、类等)

4、返回的是参数所代表的存储空间的实际大小(即存储参数所需要的字节数)

5、Sizeof不能返回动态分配的数组或外部数组的大小

      

2、strlen

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 charactersin string, not including the terminating null character. wcslen is awide-character version of strlen; the argument of wcslen is a wide-characterstring. wcslen and strlen behave identically otherwise.

 

大体意思就是说:

1、sizeof是函数

2、返回值类型为size_t(unsignedint)

3、参数只能为一个非空的字符串指针变量

4、计算字符串长度

 

二、例子
       char *ss = “123456”;
       sizeof(ss) -> 4;
       sizeof(*ss) -> 1;
       strlen(ss) -> 6;
       
       char ss[] = “123456”;
       sizeof(ss) -> 7;
       sizeof(*ss) -> 1;
       strlen(ss) -> 6;
 
       char ss[20] = “123456”;
       sizeof(ss) -> 20;
       sizeof(*ss) -> 1;
       strlen(ss) -> 6;
 
以上是对基本数据结构类型的操作,比较容易理解,如果是对结构体或类就复杂的多(如下:)
Struct S{
int i,
int j,
char k
};
S s;
Sizeof(S) -> 12;
Sizeof(s) -> 12;
这里会牵扯到一些内存对齐的问题,这个问题以后会详细讲到。
 
       作为形参声明:
Void fun(char pa[], char pa2[100])
{
       Sizeof(pa) -> 4;
       Sizeof(pa2) -> 4;
};
三、对比sizeof和strlen
      1、sizeof是运算符、表达式,strlen为函数
2、sizeof的返回值为size_t(unsigned int)。该类型能保证能容纳操作对象的最大字节数。
3、sizeof可以用类型作参数,而strlen只能用char*指针做参数,并且必须以‘\0’结尾。
4、sizeof获得的是字节数,strlen获得的是字符数。
5、数组做sizeof的参数不退化(依然为数组),而做strlen参数便退化为指针。
6、sizeof在编译时已经计算结果,而strlen在运行时运算结果。
由此特性可以得知,sizeof不能获得动态分配数组的尺寸,也不能获得外部数组的尺寸(如函数传入的数组)。
注:数组作为参数传递时传递的是指针而不是数组,如果想知道数组长度,必须增加一个参数,表示数组长度。
7、结构体、联合体和类的内存对齐机制会对sizeof产生影响。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值