CPP - using * or & to return address

痴心易碎 提交于 2021-01-29 17:56:04

问题


I am writing a code to make a linked list. one of the function I wrote in order to make a linked list easier in the main function was[node is the name of a struct conatains a.data b.pointer name next) :

    node& create_node(int value)
    {
    node newitem;
    newitem.data=value;
    newitem.next=NULL;
    return (newitem);
    };

When I write the function like this everything is ok but I want to write the function header as :

    node * create_node(int value)

But when I write it that way and I write

  return *newitem;

I get an error. I wanted to ask why the VS shows me an error in the 2nd way and what is the difference between using * and & [I already read here about references but I don't understand why one should use it in functions as , from what I understood using references takes additional space and not contributing ] .

edit :thank you for help, when I posted this it was before I even ran a test on the main function only tried to avoid mistakes before compilation . It took me some time but now I see the fundamental mistake I did .


回答1:


If you want to return a pointer you should use a pointer:

node* create_node(int value)
{
    node *newitem = new node;
    newitem->data = value;
    newitem->next = NULL;
    return newitem;
};

Also please consider who'll delete the object then.




回答2:


Your code returns a reference to a variable.

Unfortunately you return a reference to a local variable. This will fail, because the local variable will be destroyed uppont returning, but the caller will still try to reference it (that's UB) !

So if you want to return a reference, you shall make sure the object still exist:

node& create_node(int value) { 
    node* newitem = new node;
    newitem->data=value;
    newitem->next=NULL;
    return (*newitem);  // return the objet: this will be then be converted to a reference
}

You could also work with pointers as suggested by another answer. However in this case, I'd opt for shared_ptr:

shared_ptr<node> create_node(int value) { 
    node* newitem = new node;
    newitem->data=value;
    newitem->next=NULL;
    return (shared_ptr<node>(newitem)); 
}



回答3:


You should return &newitem.

But given the fact that your newitem is only available in this function's scope, the returned pointer will point to a destroyed object, so "nothing", or rather it will result in undefined behavior.

I guess you want your newitem to be created dynamically.

node * create_node(int value)
{
    node * newitem = new node;
    newitem->data=value;
    newitem->next=NULL;
    return newitem;
};


来源:https://stackoverflow.com/questions/29309414/cpp-using-or-to-return-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!