Home > Enterprise >  identifier "Node" is undefined in Linked list
identifier "Node" is undefined in Linked list

Time:02-14

This is my program to insert linked lists and print them. I'm getting error in void Insert(int x) function where I point temp variable to a new node. The error its showing is identifier "Node" is undefined. What am I supposed to do?

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

struct Node{
    int data;
    struct Node *next;
};
struct Node* head;  //global variable head

void Insert(int x){
    
    struct Node* temp=(Node*)malloc(sizeof(struct Node));
    temp->data=x;
    temp->next=head;  //it is the same as temp->next=NULL
    head=temp;
    
}

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

int main() {
    head = NULL;   
    printf("How many numbers?\n");
    int n,i,x;
    scanf("%d",&n);
    for(i=0;i<n;i  ){
        scanf("%d",&x);
        Insert(x);   
        Print();    
    }
        
    return 0;
}

CodePudding user response:

You cast the void* returned by malloc to Node*, but there is no Node type.

Here:

struct Node* temp=(Node*)malloc(sizeof(struct Node));
//                ^^^^^^^

You also do not need to cast the return from malloc. Example:

struct Node* temp = malloc(sizeof *temp);

If you'd like to use Node instead of struct Node, you can typedefine it:

typedef struct Node Node;

struct Node {
    int data;
    Node *next; // struct not needed because Node is `typedef`ined
};

You could then also do:

Node* temp = malloc(sizeof *temp);

CodePudding user response:

its called forward declaration

struct Node;
struct Node{
    int data;
    struct Node *next;
};
  • Related