0
votes
#include<stdio.h>
#include<stdlib.h>
void print();
void insert(int);
struct node
{
    int data;
    struct node* next;
};
struct node* head;
void insert(int x)
{
    struct node* temp=(node*)malloc(sizeof(node));
    temp->data=x;
    temp->next=head;
    head=temp;
}
void print(void)
{
    struct node* temp=head;
    printf("the linked list is:\n");
    while(temp!=NULL)
         {
             printf("%d ",temp->data);
            temp=temp->next;

         }
         printf("\n");
}
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();
    }
return 0;
}

comiling error says "node undeclared" first use in program,although i made "node" a global one this code is just for creating a linked list and adding user input values into the front of the linked list insert(int x) function does the insertion work.

3
you don't have a global var node, only head - Ingo Leonhardt
struct node* temp=(node*)malloc(sizeof(node)); --> struct node* temp=malloc(sizeof(struct node)); - LPs
Take care of freeing the mallocated memory before the end of program.. - LPs
a bit of vertical spacing, like around struct definitions, code blocks, function prototypes, etc would make the posted code massively easier to read. - user3629249
there are only two valid signatures for the the main() function. (regardless of the poorly written microsoft C compiler allowing such errors) those two signatures are: int main( void ) and int main( int, char** ) Strongly suggest using the appropriate signature - user3629249

3 Answers

4
votes

The error message is clear enough. In the function insert you should prepand the name node with the keyword struct.

void insert(int x)
{
    struct node* temp=(struct node*)malloc(sizeof(struct node));
                       ^^^^^^                     ^^^^^^

Another way to escape the error is to use a typedef. For example

typedef struct node
{
    int data;
    struct node* next;
} node;
3
votes

I presume when you say "first use" you mean the first line of insert where you try to allocate a node. But it is not the first; outside of the definition, that is 3 lines above, where you declare head to be a struct node*. (also note that inside the definition you use struct node* as well.)

The problem is that you did not define node; you defined struct node, and that is what you need to use.

2
votes

You might be confused by C++, in which a struct tag becomes a typedef. Try this:

typedef struct node {
    int data;
    struct node* next;
} node;

Now you can just use node instead of struct node everywhere. Easier to read and easier to type.