0

I'm new to learning data stucture in C. I wrote the code as follows when following a youtube video tutorial:

#include "stdlib.h"
#include "stdio.h"

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

struct Node* head;

void Insert(int x){
    struct Node* temp = (Node*)malloc(sizeof(struct Node));
    temp->data = x;
    temp->next = head;
    head = temp;
}

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

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

But it keeps complaining

aaa.c: In function ‘Insert’:
aaa.c:12:23: error: ‘Node’ undeclared (first use in this function)
  struct Node* temp = (Node*)malloc(sizeof(struct Node));
                       ^
aaa.c:12:23: note: each undeclared identifier is reported only once for each function it appears in
aaa.c:12:28: error: expected expression before ‘)’ token
  struct Node* temp = (Node*)malloc(sizeof(struct Node));

I'm pretty new to both C and data structure. Can anyone please tell me where the problem is? The code is mainly to insert nodes at the beginning of the list. Thanks in advance.

jwong
  • 338
  • 6
  • 15

3 Answers3

4

Node type doesn't exist. However you have a type struct Node, use that or typedef a struct to Node.

2501
  • 25,460
  • 4
  • 47
  • 87
1

Node in the below line doesn't make any sense it should be (struct Node *)

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



struct Node* temp = (struct Node*)malloc(sizeof(struct Node));//Right way to use
Gopi
  • 19,784
  • 4
  • 24
  • 36
0

1) malloc can return NULL so NULL check should be there.

if(temp == NULL) return -1; //not able to allocate memory. this is error condition

2)If you include stdlib.h then no need to cast the return value of malloc function

3) It would be better to declare the structure like below:

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

now you can write "Node" instead of "struct Node"