关于vector字符数组和字符指针数组的有关问题!
关于vector<string>,字符数组和字符指针数组的问题!!!!
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> vstr;string s;
cout<<"Input some strings:"<<endl;
while(cin>>s){
vstr.push_back(s);
}
const size_t arr_size=vstr.size();
char **pstr=new char*[arr_size];
for(size_t ix=0;ix!=arr_size;++ix){
strncpy(pstr[ix],vstr[ix].c_str(),vstr[ix].size()+1); //加一为了\0
}
for(size_t ix=0;ix!=arr_size;++ix){
cout<<*pstr[ix]<<endl;
}
return 0;
}
目的: 输入任意多个字符串到vector容器,然后把每一个string都拷贝给一个字符数组。这些字符数组的指针要置于一个字符指针数组当中。
VS 2K10 没有complie time error 但push_back结束后终止~ 大神求解啊!
------解决方案--------------------
char **pstr 必须 new 多次才能初始化:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> vstr;string s;
cout<<"Input some strings:"<<endl;
while(cin>>s){
vstr.push_back(s);
}
const size_t arr_size=vstr.size();
char **pstr=new char*[arr_size];
for(size_t ix=0;ix!=arr_size;++ix){
strncpy(pstr[ix],vstr[ix].c_str(),vstr[ix].size()+1); //加一为了\0
}
for(size_t ix=0;ix!=arr_size;++ix){
cout<<*pstr[ix]<<endl;
}
return 0;
}
目的: 输入任意多个字符串到vector容器,然后把每一个string都拷贝给一个字符数组。这些字符数组的指针要置于一个字符指针数组当中。
VS 2K10 没有complie time error 但push_back结束后终止~ 大神求解啊!
------解决方案--------------------
char **pstr 必须 new 多次才能初始化:
- C/C++ code
char **pstr=new char*[arr_size]; for(int i = 0; i < arr_size; ++i) pstr[i] = new char[1024];
------解决方案--------------------
char **pstr=new char*[arr_size];
你这个二维数组,只分配了一维的内存,
然后在一个没有分配内存的char* 上执行strncpy().
程序当然崩溃了。
for(size_t ix=0;ix!=arr_size;++ix){
pstr[ix] = new char[vstr[ix].size()+1]; // 加一句,再调试一下。
strncpy(pstr[ix],vstr[ix].c_str(),vstr[ix].size()+1); //加一为了\0
}