Search code examples
cdoubly-linked-list

*head' is a pointer; did you mean to use '->'? Why am I getting this


I am getting an error because of the 20th Line. 20 | head->prev=temp; I could define struct Node head as a global pointer and then the code works. But why I am getting an error when I am defining it as a local variable in main(). Where am I going wrong? Thanks!

#include<stdio.h>
#include<stdlib.h>

struct Node{
    int data;
    struct Node* next;
    struct Node* prev;
};



void insert(struct Node** head,int x){
    struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
    temp->data=x;
    if(*head==NULL){
        *head=temp;
        return;
    }
    
    *head->prev=temp;
    
    temp->next=*head;
    *head=temp;
}

void print(struct Node* head){
    struct Node* temp=head;
    printf("List is: ");
    while(temp!=NULL){
        printf("%d",temp->data);
        temp=temp->next;
    }
    
}

void main(){
    struct Node* head = NULL;
    insert(&head,1);
    insert(&head,2);
    insert(&head,3);
    insert(&head,4);
    insert(&head,5);
    print(head);
}


Solution

  • On this line:

    *head->prev=temp;
    

    The -> operator has higher precedence than the * operator, so it parses as:

    *(head->prev)=temp;
    

    This is invalid because head is a pointer-to-pointer-to-struct, not a pointer-to-struct. You need to add parenthesis to force the * operator to apply directly to head:

    (*head)->prev=temp;
    

    Also, don't cast the return value of malloc as it can mask other errors in your code.