0
#include <stdio.h>

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

int main() {
    Node a;
    a.data = 1;
    if (!a.next) {
        printf("hello world");
    }
}

I'm writing a little linked list program to start learning c, and I'm confused as to why a.next is not null.

2 Answers 2

2

In short, whenever you allocate some memory in C (either explicitly or implicitly), the memory is initialized with whatever was there when the stack frame for your main function was created (ie. garbage). This is true of your int value as well (remove the a.data = 1 and print the value of a.data). C doesn't zero the memory it allocates for you (which makes C more efficient). As Anandha suggested, just set the pointer to NULL to avoid this problem.

Sign up to request clarification or add additional context in comments.

3 Comments

is there a way to set a default value or I have to set it to null every time I make a Node
In addition, global variable is always zero without initialization
@ljd03 struct node { int data = 0; struct node* next = 0; };
2

You should initialize the pointer with NULL, the declared pointer may contain garbage value pointing to anywhere in the memory.

So a.next=NULL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.