sizeof和strlen的比较

  1. sizeof可以用类型做参数,也可以用数组、指针,对象和函数做参数;strlen只能用char*做参数,且必须是以''\0''结尾,当数组名作为参数传入时,实际上数组就退化成指针了。

  2. sizeof返回存储对象实际占用的字节大小;strlen的功能是返回字符串的长度,遇到/0就停止,不包含/0。

  3. sizeof是运算符,其值在编译时就计算好了;strlen是函数,其值要在运行时才能计算。

下面以代码为例进行解释:

#include <iostream>
using namespace std;

void test(char p[])
{
    cout << "p: " << p << "   " << strlen(p) << "   " << sizeof(p) << endl;
    //p:             hello         5                     4
    return;
}

int main()
{
    //char p[] = "hello";
    //char* p1 = p;
    //cout << "p1: " << p1 << "   " << strlen(p1) << "   " << sizeof(p1) << endl;
    ////p1:             hello           5                        4
    //test(p);//将p传入到函数中,其退化为指针,sizeof(p)==4,指针占4个字节
    //cout << "p: " << p << "   " << strlen(p) << "   " << sizeof(p) << endl;
    ////p:             hello         5                     6


    //char p1[] = "hello\0";
    //cout << "p1: " << p1 << "   " << strlen(p1) << "   " << sizeof(p1) << endl;
    ////p1:              hello          5                        7


    //char p2[] = "hello\\0";// "\\"转义为"\",所以该部分不含\0
    //cout << "p2: " << p2 << "   " << strlen(p2) << "   " << sizeof(p2) << endl;
    ////p2:              hello\0         7                        8


    //char p3[] = "hello\\\0";
    //cout << "p3: " << p3 << "   " << strlen(p3) << "   " << sizeof(p3) << endl;
    ////p3:              hello\         6                        8


    //char p4[] = "hel\0lo";
    //cout << "p4: " << p4 << "   " << strlen(p4) << "   " << sizeof(p4) << endl;
    ////p4:              hel            3                        7


    //char p5[] = "hel\\0lo";
    //cout << "p5: " << p5 << "   " << strlen(p5) << "   " << sizeof(p5) << endl;
    ////p5:              hel\0lo        7                        8


    //char a[] = { 1,2,3,4,5 };
    ////strlen求长度遇到/0停止,而这种情况/0出现的位置不确定
    //cout << strlen(a) << "  " << sizeof(a) << endl;//警告!!!可能没有为字符串a添加终止值
    ////      值不确定             5


    //int a[] = { 1,2,3,4,5 };
    ////strlen求长度遇到/0停止,而这种情况/0出现的位置不确定
    //cout << sizeof(a) << endl;
    ////      20


    //const char *p = "hello";
    //cout << "p: " << p << "   " << strlen(p) << "   " << sizeof(p) << endl;
    ////p:             hello         5                     4
    
    int* a[10];//数组a中每个元素均为一个指针
    int b[10];//数组b中的每个元素均为一个整数
    int (*c)[10];//c为一个指针
    cout << sizeof(a) << " " << sizeof(b) << " " << sizeof(c)  << endl;
    //        40                    40                  4                    

    return 0;
}

 

posted @ 2021-04-12 13:55  封狼居胥!  阅读(243)  评论(0编辑  收藏  举报