2

I want to make the function return the address of a particular node .but the compiler is not detecting the node datatype structure i created.

struct node
{
int data;

node *link;
};

node *header,*current;
node traverse(int pos);


node *Linkedlist::traverse(int pos)
{
    int location = 0;  
    current->link = header->link;
    node *address = new node;
    address->data = NULL;
    address->link = NULL;


    while(current->link != NULL)
    {

        if(location == pos)
        {
            cout <<current->link->data <<" "<< endl; 
            address->link=current->link;
        }
        location ++;
        current->link = current->link->link;

    }


    return  address->link;
}
2
  • 2
    Since this is a C++ question, consider std::unique_ptr and/or std::shared_ptr. If you find yourself writing new and delete often then you're probably doing something wrong. Commented Jan 13, 2013 at 4:28
  • I did not understand anything from your question. Please, be more concise about what you are asking. Also, your code seems to have too much faults and bad practices. Commented Oct 22, 2017 at 12:47

2 Answers 2

5

Change

return  *address;

to

return  address;
Sign up to request clarification or add additional context in comments.

Comments

1

As address is a pointer variable to node, you need to simply return the variable.

A * preceding a pointer variable is an explicit referencing, which means to get the value pointed by the pointer variable address. This is antagonistic to what the operator & would have done, fetch the address of a variable.

return  address;

So its logical that you should return the variable instead of returning the value pointed by the variable.

Note, care needs to be taken by the caller of traverse to free the memory explicitly by calling delete else this would result in memory leak. This is because of a potential design issue, where you have allocated a heap object inside a local scope and returned the address.

node * foo = Linkedlist::traverse(n);
...............
delete foo;

You could have simply created the object in the heap or add it as a class member, where in the former case, you can easily transfer the ownership of the object from one scope to another, where in the second case, the lifetime of the object would have been controlled by the object Linkedlist

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.