io10
io10

Reputation: 45

Null pointer when working with linked list

i cannot figure out why NULL is not printed

#include "stdio.h"
#include "stddef.h"

typedef struct{

    int info;
    struct DEMO1* next;
} DEMO1;

int main()
{
    int temp;
    DEMO1 *head ;
    if(head==NULL)
    printf("NULL");
}

Upvotes: 0

Views: 109

Answers (3)

Ron Burk
Ron Burk

Reputation: 6231

The real life lesson here is that your compiler probably had the ability to inform you that head was used before it was initialized. If you did not see such a message, then either you have a fairly poor compiler, or you have not asked the compiler to warn you about all possible problems. Find out how to get all the help your compiler is capable of offering and you could save a lot of time in your programming.

Upvotes: 1

Joel
Joel

Reputation: 4762

Your problem is that you haven't initialized the head pointer to any value.. It just contains whatever bytes were stored there previously (unless the OS was nice and did some clean up). You need to initialize head to NULL if you would like that if-statement to evaluate to true:

int main()
{
    DEMO1 *head = NULL;

    if(head==NULL)
        printf("NULL");
}

Upvotes: 1

aardvarkk
aardvarkk

Reputation: 15986

Memory is not initialized upon allocation. You cannot expect it to have a particular value until you set it.

Upvotes: 3

Related Questions