2

Why am I getting this warnings in my insertNode():

warning: assignment from incompatible pointer type [enabled by default]|

in this line:

 head->next = newNode; //point head's next to the newNode

and

warning: initialization from incompatible pointer type [enabled by default]|

in this line:

 Node *current = head->next; 

In my main() function I have also this warning:

warning: passing argument 1 of 'insertNode' from incompatible pointer type [enabled by default]|

in this line:

insertNode(&head, num);

I have a bunch of others similar to these warnings in my code. How can I fix them?

 typedef struct NodeStruct{
      int data;
      struct Node *next;
 }Node;

void insertNode(Node *head, int data){
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->data = data;

    if(head->next == NULL){
        head->next = newNode; 
        newNode->next = NULL;
    }

    else{
        Node *current = head->next; 
        while(current != NULL && current->data < data){
            current = current->next;
        }
        newNode->next = current->next;
        current->next = newNode; 
    }
}

int main(int argc, char *argv[])
{
    Node *head = malloc(sizeof(NodeStruct));
    head->next = null;
    insert(head, 22);
    insert(head, 55);
    insert(head, 44);
    insert(head, 2);
    insert(head, 2112);
    insert(head, 3);


    printList(head);
    return 0;

}
  • Can you show the structure definition. And `insertNode(&head, num);` -> `insertNode(head, num);` – Haris Oct 29 '15 at 05:13
  • @haris, why should `head` be without `&` ? –  Oct 29 '15 at 05:15
  • Because `head` is a pointer to `Node` and thats what you are receiving in `insertNode(Node *head, int data)` – Haris Oct 29 '15 at 05:16
  • @Haris, how can I fix incompatible types though? –  Oct 29 '15 at 05:17
  • I think the other warnings are because of the one mistake i pointed above. Correct that and check once plz. – Haris Oct 29 '15 at 05:20
  • Also, `Node *newNode = (Node *)malloc(sizeof(Node));` is much better as `Node *newNode = malloc(sizeof *newNode);`. See http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – user4520 Oct 29 '15 at 08:29

1 Answers1

1

In main-

insertNode(&head, num);
           ^ don't pass address

It expects Node * , you should call it like this -

insertNode(head, num);

And other warnings are because of the above mistake as you pass address of head instead of passing head to function .

Also in struct NodeStruct change this -

struct Node *next;         // you cannot reference Node in struct itself

To -

struct NodeStruct *next;   //You need to use structure name 
ameyCU
  • 16,489
  • 2
  • 26
  • 41