sizeof与strlen的区别

作者: 安然_fc00 | 来源:发表于2017-03-20 22:13 被阅读70次

先看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

相关文章

  • C++复习--点点知识点

    1.strlen与sizeof的区别? a.strlen是一个函数,sizeof是一个运算符; b.strlen返...

  • C++笔记(一)--sizeof与strlen的使用

    Day:2018.1.14 ● sizeof()与 strlen()的区别 -- sizeof()是运算符,参数可...

  • 2017C++面试题

    1.sizeof和strlen的区别 sizeof和strlen有以下区别:  sizeof是一个操作符,str...

  • sizeof与strlen的区别

    1.sizeof操作符的结果类型是size_t,它在头文件中typedef为unsigned int类型。该类型保...

  • sizeof与strlen的区别

    先看msdn的官方解释: strlen——get the length of a string.size_t st...

  • 学习sizeof,strlen区别

    strlen:从首元素开始,到结束符截止的长度,结束符不算("\0")遇到这个结束sizeof:测数据类型的长度,...

  • strlen与sizeof

    strlen strlen是函数 头文件: 作用:计算字符串的长度,不包括'\0'在内 strlen的参数只能是c...

  • strlen与sizeof

    刚刚遇到一个很有意思的事,我想给一个字符串动态分配空间,空间的大小使用sizeof来计算,然而结果却是无论输入的字...

  • strlen和sizeof的区别

    [引]:21aspnet的优质文章 1. 概念解释 strlen strlen(...)是函数,要在运行时才能计算...

  • strlen, sizeof(), length的区别

    strlen C,C++语言中的函数,用于计算当前指针变量 const char * (字符串)的字符串长度,以\...

网友评论

    本文标题:sizeof与strlen的区别

    本文链接:https://www.haomeiwen.com/subject/yrointtx.html