您的位置:首页 > 编程语言 > C语言/C++

C++中char类型数组的长度问题

2017-11-23 15:57 260 查看
char* a =new char[30];
cout<<"未初始化char数组--sizeof = "<<sizeof(a)<< endl;
cout<<"未初始化char数组--strlen = "<<strlen(a)<< endl;
cout<<"**************************"<<endl;
char* b = "hello";
cout<<"hello 数组--sizeof = "<<sizeof(b)<< endl;
cout<<"hello 数组--strlen = "<<strlen(b)<< endl;
cout<<"**************************"<<endl;
char* c;
cout<<"char数组指针--sizeof = "<<sizeof(c)<< endl;
//cout<<"char数组指针--strlen = "<<strlen(c)<< endl;  编译通过,运行出错
cout<<"**************************"<<endl;
char* d =new char[30];
d = "hello";
cout<<"为已开辟空间的数组赋值--sizeof = "<<sizeof(d)<< endl;
cout<<"为已开辟空间的数组赋值--strlen = "<<strlen(d)<< endl;
cout<<"**************************"<<endl;
char* e =new char[30];
e[0] = 'h'; e[1] = 'e';e[2] = 'l';e[3] = 'l';e[4] = 'o';e[5] = '\0';
cout<<"hello 数组 分配的内存未填满,且加\0--sizeof = "<<sizeof(e)<< endl;
cout<<"hello 数组 分配的内存未填满,且加\0--strlen = "<<strlen(e)<< endl;
cout<<"**************************"<<endl;
char* ee =new char[30];
ee[0] = 'h'; ee[1] = 'e';ee[2] = 'l';ee[3] = 'l';ee[4] = 'o';ee[5] = '\0';
ee[6] = '\0';
cout<<"两个\\0的char数组--sizeof = "<<sizeof(ee)<< endl;
cout<<"两个\\0的char数组--strlen = "<<strlen(ee)<<endl;
cout<<"**************************"<<endl;
char* eee =new char[30];
eee[0] = 'h'; eee[1] = 'e';eee[2] = 'l';eee[3] = 'l';eee[4] = 'o';
cout<<"未手动添加\\0的char数组--sizeof = "<<sizeof(eee)<< endl;
cout<<"未手动添加\\0的char数组--strlen = "<<strlen(eee)<<endl;
cout<<"**************************"<<endl;
char* eeee =new char[30];
for(int i =0;i<30;i++)
{
eeee[i] ='h';
}
cout<<"数组分配内存填满,未加\\0--sizeof = "<<sizeof(eeee)<< endl;
cout<<"数组分配内存填满,未加\\0--strlen = "<<strlen(eeee)<< endl;
cout<<"**************************"<<endl;
char* eeeee =new char[30];
for(int i =0;i<29;i++)
{
eeeee[i] ='h';
}
cout<<"数组分配内存填满,加\\0--sizeof = "<<sizeof(eeeee)<< endl;
cout<<"数组分配内存填满,加\\0--strlen = "<<strlen(eeeee)<< endl;
cout<<"**************************"<<endl;
string s("hello");
cout<<"hello string--sizeof = "<<sizeof(s)<< endl;
cout<<"hello string--strlen = "<<strlen(s.c_str())<< endl;

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: