Home > Software design >  CPP Error: Dereferencing NULL for link list
CPP Error: Dereferencing NULL for link list

Time:11-04

Can anyone help me with below errors cuz I can't find where did I go wrong...

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

struct node
{
  int data;
  struct node *link;
};

int main()
{
  node *head = (struct node*)malloc(sizeof(struct node));

  head -> data = 99;

Warning C6011 Dereferencing NULL pointer 'head'. Link_list_2

head -> link = NULL; 

node* next = (struct node*)malloc(sizeof(struct node));
next -> data = 89;

Warning C6011 Dereferencing NULL pointer 'next'. Link_list_2

next->link = NULL;
head->link = next;


printf("%d\t%d", head->data,next->data);
return 0;
}

CodePudding user response:

Try instead of node *head = (struct node*)malloc(sizeof(struct node)); this line:

node *head=new node;. Same for next.

Explanation: To create dynamic structures (that struct means that you want to create a dynamic list or something similar) you use new to allocate that node inside the dynamic memory. This line node *head=new node; means "create a node pointer called head that points to a node struct and do it at dynamic memory"

  •  Tags:  
  • c
  • Related