关于STRLEN的一个小问题
来源:百度知道 编辑:UC知道 时间:2024/06/05 08:47:59
请各位看下面一段代码,复制字符串。
#include <iostream.h>
#include <string.h>
char *strcopy(const char* b)
{
int n=strlen(b);
cout<<n<<endl;
char *a;
a=new char[strlen(b)+1];
cout<<strlen(a)<<endl;
for(int i=0;b[i]!='\0';i++)
a[i]=b[i];
a[i+1]='\0';
return a;
}
void main()
{
char*b="wuyijun";
char*c=strcopy(b);
for(int j=0;j<=strlen(c);j++)
cout<<c[j]<<endl;
return;
}
为什么strlen(b)和strlen(a)一个是7一个是17呢?
#include <iostream.h>
#include <string.h>
char *strcopy(const char* b)
{
int n=strlen(b);
cout<<n<<endl;
char *a;
a=new char[strlen(b)+1];
cout<<strlen(a)<<endl;
for(int i=0;b[i]!='\0';i++)
a[i]=b[i];
a[i+1]='\0';
return a;
}
void main()
{
char*b="wuyijun";
char*c=strcopy(b);
for(int j=0;j<=strlen(c);j++)
cout<<c[j]<<endl;
return;
}
为什么strlen(b)和strlen(a)一个是7一个是17呢?
char *a;
a=new char[strlen(b)+1];
cout<<strlen(a)<<endl;
新申请的内存要初始化的,不然里面的东西你无法判断的,这种做法没有必要,如果想要输出strlen(a),可在拷贝结束后用strlen(a);
另楼上用sizeof的做法是不对的,对指针是不可以用sizeof来获取字符串的长度的
你这么做没意义啊?你是想看看他分配了多大内存?需要用sizeof 察看分配总的内存数,strlen以/0为结束计算字符串的长度。
a 刚分配内存后头没有写0结束符