注册 登录
编程论坛 C++教室

[求助] 关于指针数据返回的问题

boris250 发布于 2007-10-21 09:24, 464 次点击
在编写两个string字符串合并的函数时,我用mallco重新开辟了一段内存地址,并进行赋值,请问如何返回这段内存地址的数据给string c!!!
程序如下:
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
int lenght(string a) //计算string字符长度函数
{
char *p;
p=&a[0];
int i=0;
while(*p!='\0')
{
i=i+1;
p=p+1;
}
return i;
}
stirng stringcmp(string a,string b)
{
cin>>a>>b;
string c;
int i;
char *p;
char *q;
char *s;
p=&a[0];q=&b[0];
int len1=lenght(a),len2=lenght(b);
s=(char*)malloc((len1+len2)*sizeof(char));//开辟一段内存地址
for(i=0;i<(len1+len2);i++)
{
if(i<len1)
{
*s=*p;
s=s+1;
p=p+1;
}
if(i>=len1)
{
*s=*q;
s=s+1;
q=q+1;
}
}
return(c); 如何返回s所定义的内存地址的数据给string c。
}

[此贴子已经被作者于2007-10-21 9:32:20编辑过]

3 回复
#2
HJin2007-10-21 10:29

int lenght(string a) //计算string字符长度函数
{
char *p;
p=&a[0];
int i=0;
while(*p!='\0')
{
i=i+1;
p=p+1;
}
return i;
}

Simply put, you are doing the wrong thing. Since you used the
STL string class, all you need to do is

return a.size();

or

return a.length();

Why is that? Because not all STL implementations for strings use
a null-terminated scheme; i.e., this may be an infinite loop:

while(*p!='\0')

#3
jxnuwy042007-10-22 12:51
两个字符串合并的算法有必要写的这么麻烦吗?
string Connect(string a,string b)
{
string a;
string b;
string c=a+b;
return c;
}
#4
aipb20072007-10-22 19:31
楼主想合并的应该是char*字符串吧,

用string的话就该用stl的方法!
1