struct Person {
std::string name;
int id;
};
struct Community {
std::string name;
Person people[2];
};
Community* makeCommunity() {
Community* c = (Community*)operator new(sizeof(Community), std::nothrow);
if(!c) {
std::cout << "Failed to allocate" << std::endl;
std::exit(0);
}
c->name = "Community Name";
c->people[0].name = "Person1";
c->people[0].id = 1;
//Run-time encountered here.
c->people[1].name = "Person2";
c->people[1].id = 2;
return c;
}
I'm currently learning C++ and I was testing code similar to above code when the program encountered a runtime error and crashed when it tries to execute c->people[1].name = "Person1";
in the aforementioned function. Yet, this works fine when I allocate memory as:
Community* c = new Community(std::nothrow);
I am puzzled by that fact that c->people[0].name = "Person1";
executes perfectly, but c->people[1].name = "Person2";
fails at runtime when memory is allocated for Community
as:
Community* c = (Community*)std::operator new(sizeof(Community), std::nothrow);
Can someone shed some light on this?