Sunday 15 August 2010

c++ - initializing array of string in binary search tree -



c++ - initializing array of string in binary search tree -

my node contains int , string variable, , tried using binary search tree. code follow:

struct node{ int a; string members[5]; }; int main(){ node * root = null; root = (node*)malloc(sizeof(node)); root->members[0] = "aaaaa"; homecoming 0; }

of course, code wasn't that, made short in main because want show problem. gave me 'access violation writing location'. tried using 'new node();' instead of malloc , didn't happen. why exactly?

malloc() allocates memory. doesn't phone call constructor of object. phone call constructor on allocated memory using, e.g.

void* mem = malloc(sizeof(node)); if (mem) { node* root = new(mem) node; // ... }

when using new node instead of malloc(sizeof(node) allocate memory gets initialized. using uninitialized object undefined behavior.

c++ c string tree binary-search-tree

No comments:

Post a Comment