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

string pointer的问题

loriwang 发布于 2007-09-19 23:04, 554 次点击

想把一个string赋值到new string返回的地址空间

string s1="hello,world";
string s2=new string;
for(unsigned int i=0;i<=s1.length();i++) s2[i]=s1[i];

编译ok,但运行error,好像是指向了非法地址,这是什么道理?

2 回复
#2
HJin2007-09-19 23:22
回复:(loriwang)string pointer的问题

You made more than 1 mistake here.
=======================================

#include <iostream>
#include <string>
using namespace std;

int main()
{
string s1 = "hello,world";
string* s2 = new string;
s2->resize(s1.size());
for (unsigned int i = 0; i < s1.length(); i++)
{
s2->at(i) = s1[i];
}
cout << * s2 << endl;

return 0;
}

#3
loriwang2007-09-20 00:31

er.... resize(), at() function and C++ style string. I have checked some documents and I found that I confused char pointer and char array with string pointer and string. Thx HJin.

1