如何用C++new分配字符串

来源:百度知道 编辑:UC知道 时间:2024/07/07 13:56:36
如果要用一个new来分配字符串,假如用 new char[N] 来分配,则需要提前指明字符串大小,能不能不用提前指明字符串大小呢? new string是不是满足这个条件?

char *a=new char(); int* b=new int();
char *a=new char; int* b=new int;
前两种是不是效果一样,只能分配一个字符(或者int)大小的空间?
但是我编译下面程序,发现也能赋值字符串,没问题啊,怎么回事?下面这样做是不是很有风险,只是某些情况不会编译输出出错?
int main()
{
char *a=new char();
char *c=new char;
(*a)='1';
*(a+1)='s';
*(a+2)='3';
strcpy(c,"abc");
cout<<a<<endl;
cout<<c<<endl;
delete []a;
system("pause");
}

str=NULL;
1楼的要加这个 要不然就产生野指针了

也可以不new
string str;
cin>>str;
cout<<str<<endl;

或者先统计输入字符串大小 然后new[...]多少个char出来存储

是的,你这么做风险很大,叫做指针越界。我在VC6.0运行你的程序就出现运行错误!!!

用 new string 好一些。

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

void main()
{
string *str = new string;
cin>>*str;
cout<<*str<<endl;
delete str;
}