mercredi 22 juin 2022

Pushing non dynamically allocated objects to a vector of pointers

I've been trying to figure out this issue while I was coding on Codeblocks but didn't have any luck.

So basically I have the following code inside a function:

Node * newNode;
newNode->data = num;
//root is defined somwhere at the top as 'Node * root';
root->adj.push_back(newNode);

and the following struct:

struct Node{
    int data;
    vector<Node*> adj;
};

When I do the push_back to the vector the program just cycles for 2-3 seconds and exits with a non-zero exit code. If I allocate the memory dynamically It seems to work correctly. Does the program somehow blow up when the pointer is not pointing to a specific block of memory?

Aucun commentaire:

Enregistrer un commentaire