简体   繁体   中英

Queue implementation is losing track of head node

I have a queue add function implemented

void queue::add(myObj info)
{
    node* node = new node;

    node->info = &info; //<---suspect
    node->next = NULL;

    if(head == NULL){
        head = node;
    }
    else{
        tail->next = node;
    }
    tail = node;
    count++;

}

Every time this gets visited the head node's data points to whatever I'm passing in. I realize there is a template for this but I am trying to build one, because I obviously need practice.

I am trying to keep all the pointers pointed to the original objects. I wanted to pass in the object and point to the refrence.

The node is a struct with myObj * info and node * next

info is a parameter of your function, that is passed by value. In this case, &info is the address of the parameter, and not of the original data.

This is undefined behaviour and can only give weird results.

One possible solution would be:

void queue::add(myObj& info)  // pass by reference
{
    ... // unchanged code
}

In this case, &info would refer to the address of the original object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM