sizeof与strlen的区别

先看msdn的官方解释:

strlen——get the length of a string.
size_t strlen(const char *string);
Each ofthese functions returns the number of characters instring, notincluding the terminating null character.
//函数返回string里的字符数,不包括终止字符'\0'

sizeof
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or atype (including aggregate types). This keyword returns a value of type size_t.
//返回变量或类型(包括集合类型)存储空间的大小

When appliedto a structure type or variable,sizeof returns the actual size, whichmay include padding bytes inserted for alignment. When applied to a statically dimensioned array,sizeof returns the size of the entire array. The sizeofoperator cannot return the size of dynamically allocated arrays or externalarrays.
//应用结构体类型或变量的时候,sizeof()返回实际大小,包括为对齐而填充的字节。当应用到静态数组时,sizeof()返回整个数组的大小。sizeof()不会返回动态分配数组或扩展数组的大小。

sizeof与strlen有以下区别:

  • sizeof是一个操作符,而strlen是库函数。
  • sizeof的参数可以是数据的类型,也可以是变量,而strlen只能以结尾为'\0'的字符串作参数。
  • 编译器在编译时就计算出了sizeof的结果,而strlen必须在运行时才能计算出来。
  • sizeof计算数据类型占内存的大小,strlen计算字符串实际长度。

练习

char str[]="hello";
char *p=str;
int n=10;
//请计算
sizeof(str);
sizeof(p);
sizeof(n);
void func(char str[100])
{
    sizeof(str);
}
void *p=malloc(100);
sizeof(p);

答案

char str[]="hello";
char *p=str;
int n=10;
//请计算
sizeof(str);//6,5+1=6,1代表'\0'
sizeof(p);//4,代表指针
sizeof(n);//4,整形占据的存储空间
void func(char str[100])
{
    sizeof(str);//4,此时str已经转换为指针了
}
void *p=malloc(100);
sizeof(p);//4,指针大小

sizeof

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.在C/C++中实现本地方法 生成C/C++头文件之后,你就需要写头文件对应的本地方法。注意:所有的本地方法的第...
    JayQiu阅读 2,451评论 0 3
  • Jni数据类型 Jni方法 来自 http://blog.chinaunix.net/uid-22028680-i...
    FlyDragonInSky阅读 958评论 0 0
  • 一、(一共三十题) 1.main() { int a[5]={1,2,3,4,5}; int *ptr=(int ...
    iOS_Alex阅读 1,013评论 0 0
  • 带着强烈预感入梦,仍旧重复昨天的梦境。 七月夏日的高空,云朵大朵连绵,厚厚重重遮掩。自身依旧变幻。 我仿佛参与者,...
    凭你矣阅读 199评论 0 0
  • 想念,我的 都是从夜深开始 北京的天 偶尔会看见月亮 今天没有 我第一个爱的人 第一个为我正领子的人 不是同一人 ...
    江宥祀阅读 170评论 0 0