0

I got run-time error for the following code. I am just starting to get familiar with linked list. Can any one point out what's the problem here? thanks

#include "stdafx.h"
#include<iostream>
using namespace std;

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

node* buildonetwothree()  
{
node* head=NULL;          
node* second=NULL;        
node* third=NULL;         


head->data=1;
head->next=second;

second->data=2;
second->next=third;

third->data=3;
third->next=NULL;
return head;           
}


int length(node* head) 
{

node* moving=head;
int count=0;
while(moving!=NULL)    
{moving=moving->next;
count++;}
return count;
}

void main()
{
node* head=NULL;
head=buildonetwothree();
cout<<length(head);

}
2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by gerard4143
0

You haven't allocated any memory for your pointers

node* buildonetwothree()
{
node* head=NULL;
node* second=NULL;
node* third=NULL;

head->data=1;

head->next=second;
second->data=2;
second->next=third;
third->data=3;
third->next=NULL;

return head;
}

Edited by gerard4143: n/a

0

thanks, I changed

node* head=NULL;         
node* second=NULL;       
node* third=NULL;

to

node* head=new node;  
node* second=new node;
node* third=new node;

now it works, but where should I deallocate the dynamic allocated memory? at the end of the main program?

0

thanks, I changed

node* head=NULL;         
node* second=NULL;       
node* third=NULL;

to

node* head=new node;  
node* second=new node;
node* third=new node;

now it works, but where should I deallocate the dynamic allocated memory? at the end of the main program?

You really should implement your nodes as classes and let the destructor's worry about freeing up allocated memory..

Edited by gerard4143: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.