I am trying to dynamically allocate an array of struct in another struct here is the code segment
I don't get any syntax errors but I get segmentation fault once I try to enter str1
could someone explain why is there a segmentation fault, and what happens in memory in the dynamic allocation in such situation
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);
}
mallocinstead ofnew? Generally, if you're programming in C++, you want to actually use C++.cinorcoutand don't cast the return frommalloc. If you're writing C++, don't usemallocat all, and usestd::vectorinstead of your home-rolled imitation.