#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
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.
3 Comments
You should initialize the pointer with NULL, the declared pointer may contain garbage value pointing to anywhere in the memory.
So a.next=NULL