我尝试在另一个结构中动态分配一个结构数组,这里是代码段
我没有收到任何语法错误,但一旦我尝试输入str1,就会出现分段错误
有没有人能解释一下为什么会出现分段错误,以及在这种情况下动态分配内存会发生什么情况
struct A {
string str1;
string str2;
}
struct B {
int count;
A* A_array;
}
void GetB (B** b)
{
*b = (B*) malloc(1*sizeof(B));
cout << "Enter count";
cin >> (**b).count;
(**b).A_array = (A*) malloc((**b).count*sizeof(A));
cout << "Enter str1";
cin >> (**b).A_array[0].str1;
cout << "Enter str2";
cin >> (**b).A_array[0].str2;
}
int main(){
B* b;
GetB(&b);
}
发布于 2013-03-08 17:25:17
发生崩溃的原因是因为string str1;
string str2;
没有正确构建。
而且它们没有正确构造,因为malloc
只分配内存,而不调用构造函数。
这就是C++中运算符new
的作用。
malloc
来分配非POD对象。malloc
。std::vector
来代替<代码>H213<代码>G214发布于 2013-03-08 21:16:41
在我的评论的基础上,这将等同于您当前使用一些更常用的C++的程序。我故意让结构尽可能接近你的原始结构,但当然还有其他问题需要考虑,比如你的类应该有构造函数还是私有成员。
struct A {
string str1;
string str2;
};
struct B {
int count;
vector<A> A_vec;
};
B GetB ()
{
B myB;
cout << "Enter count";
cin >> myB.count;
A a;
cout << "Enter str1";
cin >> a.str1;
cout << "Enter str2";
cin >> a.str2;
myB.A_vec.push_back(a);
return myB;
}
int main(){
B b(GetB());
}
https://stackoverflow.com/questions/15299698
复制相似问题