0

SO, I'm trying to write a generic singly linked list implementation that works with all types, and keep coming across the error of: Assignment from incompatible pointer type for the line of code that is as follows:

node->next = newNode;

This is in the context of the following declarations and structs:

typedef struct{
    void* data; // The generic pointer to the data in the node.
    Node* next; // A pointer to the next Node in the list.
} Node;

void insertAfter(Node* node, Node* newNode){
    // We first want to reassign the target of node to newNode
    newNode->next = node->next;
    // Then assign the target of node to point to newNode
    node->next = newNode;
}

I have tried to use both this: node->next = *newNode; and this: node->next = &newNode; But as you can imagine, they do not work, what am I doing wrong here, what and why is this error being caused and how do I fix it?

2
  • What compiler are you using? Commented Nov 8, 2013 at 3:05
  • The struct definition you posted is not compilable. You cannot refer to not-yet-defined type Node inside that typedef-struct definition for type Node. This will immediately trigger a compile error. Either you have another definition for some other type Node somewhere, or the code you posted is not the code you compiled. And if you really had another type Node declared somewhere you'd typically get a compile error for type redefinition. So, I'd guess that the code you posted is inaccurate. Commented Nov 8, 2013 at 3:33

1 Answer 1

1

Change the definition of your struct from

typedef struct{
    void* data; // The generic pointer to the data in the node.
    Node* next; // A pointer to the next Node in the list.
} Node;

to

typedef struct Node Node;
struct Node {
    void* data; // The generic pointer to the data in the node.
    Node* next; // A pointer to the next Node in the list.
};

Reason being that you can not reference the typedef inside your struct until the typedef is complete.

Not sure why you thought the other line was the issue. It was not.

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

1 Comment

Well, true, "you can not reference the typedef inside your struct until the typedef is complete". But the OP reports a completely different error, which suggests that his typedef/struct definition actually compiles(!) Something is amiss here.

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.