Ironicism
Ironicism

Reputation: 7

C - linked list cannot convert node** to node*

I was studying linked lists and copying my examiners notes exactly and couldn't get it to work. The error says that I

cannot convert 'node**' to node*'.

I have tried changing the types so that they match but that just causes it to crash once I run it. If someone could give me some insight into why this is happening it would be much appreciated.

#include <stdlib.h>


struct node
{
    int number;
    struct node *next;
}*head;

main(){
    int i;

    node *n1, *n2, *temp;

    temp = n1;

    n1->number = 1;
    n1->next = &n2;

    n2->number = 2;
    n2->next = NULL;



   return 0;

}

Upvotes: 0

Views: 5537

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Your problem is here

n1->next = &n2;

change to

n1->next = n2;

Reason behind this is, the types of the variables involved. n1->next is of type struct node *, so as n2. &n2 will be of type struct node **

However, still this instruction will be erroneous [and your program / code snippet produces undefined behaviour], since n1 and n2 are both unitialized till this point. NOTE

  • Allocate memory for n1, n2 using malloc() [or family]
  • Atleast consider initializing n1,n2, temp to NULL[and all other local variables also, for that matter].

Note: Related readings,

  • For read-before-write in temp = n1; and for using uninialized memory n1->number

From chapter 6.7.8, paragraph 10, C99 standard

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

and , Annex J of the same document, from J.2

The value of an object with automatic storage duration is used while it is indeterminate

Upvotes: 2

sidrakesh
sidrakesh

Reputation: 234

The major problem lies with the statement:

n1->next = &n2;

Here, n->next is of type node* (see the definition of struct node, you will find that it has a member next has type struct node*), whereas, you are assigning &n2 to it, which is a pointer to n2. n2 itself is a pointer variable to the type struct node, therefore, &n2 is a pointer to a pointer to struct node type.

This leads to a type mismatch and hence, the error.

Other issues would be that n2 is not initialized when assigning it to n1->next, n1 is not initialized when assigning it to temp.

Upvotes: 2

Related Questions