Hillary Rodham Clinton
Hillary Rodham Clinton

Reputation: 119

"cannot convert 'SinglyLinkedList<int>::node*' to 'int*' in assignment compilation terminated due to -Wfatal-errors."

Error

t.cpp: In constructor 'SinglyLinkedList::SinglyLinkedList(T*, size_t) [with T = int]': t.cpp:29: instantiated from here Line 51: error: cannot convert 'SinglyLinkedList::node*' to 'int*' in assignment compilation terminated due to -Wfatal-errors.

in the line shown below

   node * lastNode = new node;
   lastNode->val = *arr;
   lastNode->next = NULL;
   for (T * pa(arr+1), * pb(arr+n); pa != pb; ++pa)
   {
      node * thisNode = new node;
      thisNode->val = *pa;
      thisNode->next = NULL;
      lastNode->next = thisNode; // error 
      lastNode = thisNode;
      delete thisNode;      
   }

Full code is here: http://codepad.org/gZ2KnrUM

Can't figure out what is syntactically incorrect about that line.

Bonus question: Is there a way of shorthanding initialization of a struct with new? I want to be able to make lines like

node * lastNode = new node;
lastNode->val = *arr;
lastNode->next = NULL;

into a single line if possible. I know that if I was create it on the stack then I could do

node lastNode = { *arr, NULL m}; 

but is there an equivalent brace initialization for creating with new?

Upvotes: 0

Views: 2508

Answers (2)

Francisco Aguilera
Francisco Aguilera

Reputation: 3482

You're trying to assign a type of node * to a variable of type int *.

Your node code for node should be:

struct node 
{  
    T val;
    node * next;
};

As for the "shorthand initialization" I would just use a constructor.

class node 
{ 
    T val;
    node * next;

public:
    node(T val, node * next)
    : this->val(val)
    , this->next(next)
    {};
};

node * lastNode = new node(*arr, nullptr);

Or a c++11 initializer:

node * lastNode = new node { *arr, nullptr };

Upvotes: 2

user1084944
user1084944

Reputation:

The error is on the line

lastNode->next = thisNode;

and the error is that

cannot convert 'SinglyLinkedList::node*' to 'int*' in assignment

I can see that thisNode has type node*, and from the error message I conclude that next is a member variable of type int*.

Thus, either that declaration is wrong, or your idea of assigning a node* to next is ill-conceived.

Regarding your second question (which really should be a different question, rather than asking two questions at once), you can either give your struct a constructor, or upgrade to C++11 and do new node{*arr, nullptr}.

Upvotes: 1

Related Questions