C++专题:strlen和sizeof的区别

来源:互联网 发布:微小企业会计软件好吗? 编辑:程序博客网 时间:2024/05/01 14:15

转载请注明出处:http://blog.csdn.net/feng1790291543

难点:strlen主要针对与字符串;sizeof主要可对基本数据类型求字节长度(int 、double、char等等),真数组(如:str[10])和假数组(如:*str)算出的结果不一样,比如:char *str="hello"; //输出长度为4 ,它针对字符串下标的个数

char str[10]="hello";//输出长度为6(包含'\0'),它针对字符串的所有字符


#include<iostream>
using namespace std;

int main()
{
    cout<<"计算指针数组、一般字符数组的长度:"<<endl;

       char num1[]="hello";           //一般字符串数组

size_t c=strlen(num1);
    size_t c1=sizeof(num1);

cout<<"一般字符串数组(加0):"<<endl;
cout<<"--/*strlen*/--"<<c<<endl;
    cout<<"--/*sizeof*/--"<<c1<<endl;

char *num2[]={"hello","zhangsan"};  //指针数组

cout<<"指针数组(从首地址计算个数,不加0)"<<endl;
    
size_t c2=strlen(num2[0]);
    size_t c3=sizeof(num2);

cout<<"--/*strlen*/--"<<c2<<endl;
    cout<<"--/*sizeof*/--"<<c3<<endl;

    size_t c_int=sizeof(int);
size_t c_ch=sizeof(char);
size_t c_d=sizeof(double);

    cout<<"计算基本数据类型的长度:"<<endl;
cout<<"--/*sizeof*/--"<<c_int<<endl;
    cout<<"--/*sizeof*/--"<<c_ch<<endl;
cout<<"--/*sizeof*/--"<<c_d<<endl;
return 0;
}

0 0
原创粉丝点击