VD18421
VD18421

Reputation: 295

C++ linked list argument of type "Node*" incompitable

I have the following linked list in c++ program. I think its built properly.

struct Node
{
    int data;
    Node* next = NULL;
};
void addNode(Node *head, int data);

int main()
{
    struct Node
    {
        int data;
        Node* next = NULL;
    };

    Node *head = new Node;
    head->data = 3;
    addNode(head, 5);

    system("pause");
    return 0;
}


void addNode(Node *head, int data)
{
    Node *curr = head;
    while (curr->next != NULL)
    {
        curr = curr->next;
    }
    Node *newnode = new Node;
    curr->next = newnode;   
}

First I create a node struct, and then I create a head and set it to a new Node. I also just set the head->data = 3. Then I call my addNode function which takes in a Node * head, and essentially adds a node to the end of linked list. However when I pass in the head, in the statement addNode(head, 5), I get an error saying 'void addNode(Node *,int)': cannot convert argument 1 from 'main::Node *' to 'Node *'

Why is this? It doesn't make sense to me.

Upvotes: 0

Views: 859

Answers (2)

Veronika Franc
Veronika Franc

Reputation: 29

Just remove the following:

struct Node
{
    int data;
    Node* next = NULL;
};

Your problem is that you're defining a separate type with a different scope. Your compiler is thinking of the 1st definition as something analogous to global::Node, while the 2nd definition is main::Node.

So, in reality, when you assign a value to head, you are assigning incompatible types (global::Node* = main::Node*), so your compiler is throwing an error.

Upvotes: 0

m_callens
m_callens

Reputation: 6360

It is just a general scope issue. Within your addNode function, the struct Node being used is the one declared before your main(). However, the code inside of your main function uses the redefined struct Node within the scope of main...hence the error saying cannot convert main::Node* to Node*.

Remove the definition of struct Node from inside of your main and it should work.

Also, inside of your addNode function, you aren't setting the data value of the new Node, so be sure to do that as well.

Upvotes: 1

Related Questions