C/C++中strlen()、sizeof()、size()的区别

本文详细解析了C语言中strlen(), size(), sizeof()三个函数的区别及应用场景。strlen()用于获取字符串的实际长度;size()适用于容器,返回容器中元素的数量;而sizeof()作为运算符,返回变量或类型在内存中所占的字节数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

strlen()、size()、sizeof()的区别

1.strlen()

strlen是一个C语言中的一个字符串函数,使用strlen返回的是字符串实际的大小,在程序的运行过程中计算。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main()
{
    int res;

    char str1[10]="hello";
    res=strlen(str1);   //res=5
    cout << res << endl<<endl<<endl;

    char str2[]="hello";
    res=strlen(str2);   //res=5
    cout << res << endl<<endl<<endl;

    char *str3="hello";
    res=strlen(str3);   //res=5
    cout << res << endl<<endl<<endl;

    return 0;
}

运行结果如下:

可以看到,结果均等于5,说明strlen返回的均是字符串的实际长度。

2.size()

(1)在获取字符串长度的时候,size()、strlen()、length()的结果是一样的。

(2)在对容器操作时,返回的是容器中元素的个数。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;

int main()
{

    char str1[10]="hello";
    cout << sizeof(str1) <<endl;   //10

    char str2[]="hello";
    cout << sizeof(str2) << endl;  //6
    cout << sizeof(*str2) <<endl;  //1,*str2是第一个char字符,则为1
    strcpy(str2,"abc");            //给str2重新赋值为"abc",其结果仍然不会改变
    cout << sizeof(str2) << endl;  //6

    char *str3="hello";
    cout << sizeof(str3) <<endl;   //4

    int a[10];
    cout << sizeof(a) << endl;    //40

    int b;
    cout << sizeof(b) << endl;    //4

    char c;
    cout << sizeof(c) << endl;    //1

    vector <int> d(10,1);
    cout << sizeof(d) <<endl;     //12

    vector <int> e;
    cout << sizeof(e) <<endl;     //12


    return 0;
}

运行结果:

3.sizeof()

sizeof是运算符,该类型保证能容纳实现所建立的最大对象的字节大小,其值在编译时即计算好了,它的值不会随着内容的改变而发生变化,记住“不会随内容的改变发生变化”这句话,那下面这些例子就很好理解了:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;

int main()
{

    char str1[10]="hello";
    cout << sizeof(str1) <<endl;   //10

    char str2[]="hello";
    cout << sizeof(str2) << endl;  //6
    cout << sizeof(*str2) <<endl;  //1,*str2是第一个char字符,则为1
    strcpy(str2,"abc");            //给str2重新赋值为"abc",其结果仍然不会改变
    cout << sizeof(str2) << endl;  //6

    char *str3="hello";
    cout << sizeof(str3) <<endl;   //4

    int a[10];
    cout << sizeof(a) << endl;    //40

    int b;
    cout << sizeof(b) << endl;    //4

    char c;
    cout << sizeof(c) << endl;    //1


    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值