I'm getting the error:
taking address of rvalue [-fpermissive]
31 | ListNode l = ListNode(2, &ListNode(4));
when executing the following code:
#include<iostream>
class ListNode {
public:
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
int main(){
ListNode l = ListNode(2, &ListNode(4));
return 0;
}
I don't really know how to use classes in C but I would like to use a Class here for the LinkedList instead of a struct.
CodePudding user response:
You would get exactly the same error with a struct. The problem is that you are taking the address of a temporary object, here &ListNode(4)
and that's bad because the address will live longer than the object, and you end up with a pointer to an object which no longer exists.
To fix, turn the temporary object into a variable
ListNode m = ListNode(4);
ListNode l = ListNode(2, &m);
Now the ListNode(4) object is held by a variable, so it's safe to take the address of it.
But usually in a linked list class you solve this problem by using dynamic memory allocation with new
.