0

I did this code with the help of code on Youtube/freeCodeCamp.org/data structure -using C and C++. Same code worked for tutor ,but in my PC it is not working.

#include <stdio.h>
#include <stdlib.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("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, x;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        printf("Enter the number;\n");
        scanf("%d", &x);
        Insert(x);
        Print();
    }
}

Compiler output:

insertingNodeAtbegining.c: In function 'Insert':
insertingNodeAtbegining.c:12:26: error: 'Node' undeclared (first use in this function)
     struct Node *temp = (Node *)malloc(sizeof(struct Node));
                          ^~~~
insertingNodeAtbegining.c:12:26: note: each undeclared identifier is reported only once for each 
function it appears in
insertingNodeAtbegining.c:12:32: error: expected expression before ')' token
     struct Node *temp = (Node *)malloc(sizeof(struct Node));
                                ^
Clifford
  • 88,407
  • 13
  • 85
  • 165
  • you should write **(struct Node *)malloc(sizeof(struct Node));** because Node currently not defined type. – N0ll_Boy May 28 '21 at 04:28
  • If you're "using C and C++" you would be a lot better off picking one and sticking to it for now. There's small differences in the subset of the language that looks similar that can be confusing and will hinder you learning either properly. – Paul Hankin May 28 '21 at 07:12
  • `struct Node *temp = malloc(sizeof *temp);` or `struct Node *temp = malloc(sizeof(struct Node));` are superior. It's not recommended to cast the return type for malloc. https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Paul Hankin May 28 '21 at 07:16

2 Answers2

1

please add the data type struct in the 12th line, i.e.

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

Thank you for this question.

0

Same code worked for the tutor because he used C++ compiler and in your case you are using c compiler.

For compiling with c compiler modify line 12 as follows.

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

In C, you have to use struct keyword whenever you are declaring struct data type. That is not the case with C++.