sizeof与strlen

这两个的区别,记了又忘,索性通过代码记忆

#include<iostream>

using namespacestd;

int main()

{

    //字符串常量作为字符指针

    char* a = "hello";

    cout<<"length about sizeof:"<<sizeof(a)<<" "<<"lengthabout strlen:"<<strlen(a)<<endl; //(sizeof显示的是指针的大小,为4,strlen则只能从字符起始,找到\0为止,为5

 

 

    //字符数组

    char b[] = {'h','e','l','l','o'};

    cout<<"length about sizeof:"<<sizeof(b)<<" "<<"lengthabout strlen:"<<strlen(b)<<endl;//(sizeof为5,为数组元素个数,strlen为31,由于字符数组没有指定\0,strlen会一直向后找到\0元素为止)

 

 

    //以字符串常量初始化字符数组

    char c[] = "hello";

    cout<<"length about sizeof:"<<sizeof(c)<<" "<<"lengthabout strlen:"<<strlen(c)<<endl; //(sizeof为6,字符常量默认加了\0.strlen为5, strlen找到\0元素为止,但不将最后的\0元素记入计数)

 

    //定义好长度的字符数组

    char d[10]= "hello";

    cout<<"length about sizeof:"<<sizeof(d)<<" "<<"lengthabout strlen:"<<strlen(d)<<endl; //(sizeof为10,以数组设定长度为准.strlen为5, strlen找到\0元素为止,但不将最后的\0元素记入计数)

 

    char e[] = {'h','e','\0','l','l','o'};

    cout<<"length about sizeof:"<<sizeof(e)<<" "<<"lengthabout strlen:"<<strlen(e)<<endl; //(sizeof为6,为数组元素个数.strlen为2, strlen找到\0元素为止,但不将最后的\0元素记入计数)

 

 

    getchar();

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值