strlen和sizeof 的区别

下面会举一些具体的例子来说明两者的区别

  • 例子1
#include<iostream>
#include<vector>
#include<string.h>
using namespace std;
int main()
{
    char sayhello[]  = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};
    cout<<sayhello<<endl;
    cout<<sizeof(sayhello)<<endl;
    cout<<strlen(sayhello)<<endl;
    sayhello[5] = '\0';
    cout<<sayhello<<endl;
    cout<<sizeof(sayhello)<<endl;
    cout<<strlen(sayhello)<<endl;
    char *str ="abcdef";
    cout<<sizeof(str)<<endl;

}
运行结果

上面定义了一个字符数组,首先打印出sizeof(sayhello)的值为12,也就是说整个字符数组的大小是12;接下来打印了strlen(sayhello)的值为11,这个函数计算的是字符串的大小,直到'\0'才停止计算;将字符数组的第五个字符改为'\0'时,重新计算sizeof()发现其大小还是12,所以说sizeof()计算的是实际内存的大小;再计算strlen(),因为它碰到'\0'就停止,所以此时的大小变成了5;程序的最后,打印了一个指向串的指针的大小,结果显示其大小为4.

  • sizeof()是运算符,在编译时候就已经计算出了实现所需要的内存字节的大小,其参数为函数的话,其大小为函数返回类型的大小;而strlen()是个包含在头文件string.h的函数,它计算的是字符串的长度,在函数运行时候执行。
  • 例子2
#include<iostream>
#include<vector>
#include<string.h>
using namespace std;
int main()
{
    char sayhello[20]  = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};
    cout<<strlen(sayhello)<<endl;
    cout<<sizeof(sayhello)<<endl;
    char *str = "abcdef";
    cout<<strlen(str)<<endl;
    cout<<sizeof(str)<<endl;
    char str1[5] = {'a','\0'};
    cout<<strlen(str1)<<endl;
    cout<<sizeof(str1)<<endl;
    char *p = new char[8];
    cout<<strlen(p)<<endl;
    cout<<sizeof(p)<<endl;
    cout<<sizeof(*p)<<endl;


}
运行结果

对上述运行的结果进行分析,大小为20的字符数组,sizeof任然求的是字符数组所消耗的内存的大小,strlen求的是字符串的长度;str所指向的字符串的长度为6,对指针str求sizeof运算为4;指针p指向动态开辟的字符数组的首地址,对*p(指向的内容是一个char)做sizeof()运算大小为1。

猜你喜欢

转载自blog.csdn.net/qq_35353824/article/details/88427467