"Program has stopped working"
Oct 17, 2012 at 10:15pm UTC
So I'm trying to run some example functions that were given to me. The build succeeds in VS2010, but when I run the program, it crashes after a value is entered. I've tested it on two machines and the same thing happens. Here's the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
#include <iostream>
using namespace std;
struct node
{
int item;
node *next;
node *headptr;
};
bool insert (node *&headptr, int val);
void printlist(node *headptr);
int count(node *headptr);
int main()
{
do
{
int val;
node *headptr;
cout << "please enter value to be added to our list: " ;
cin >> val;
insert (headptr, val);
printlist (headptr);
}while (1==1);
}
bool insert (node *&headptr, int val)
{
node *prev;
node *temp;
node *curr;
temp = new (nothrow) node;
if (temp == NULL)
return false ;
temp->item = val;
temp->next = NULL;
//empty check:
if (headptr == NULL)
{
headptr = temp;
return true ;
}
if (temp->item <= headptr->item)
{
temp->next = headptr;
headptr = temp;
return true ;
}
prev = headptr;
curr = headptr;
while (curr != NULL && curr->item <= temp->item)
{
prev=curr;
curr=curr->next;
}
prev->next = temp;
temp->next = curr;
return true ;
}
void printlist(node *headptr)
{
node *temp=NULL;
temp=headptr;
while (temp!=NULL)
{
cout << temp->item;
temp = temp->next;
}
}
int count(node *headptr)
{
int count = 0;
node *temp=NULL;
temp=headptr;
while (temp!=NULL)
{
temp = temp->next;
count++;
}
return count;
}
Oct 18, 2012 at 12:12am UTC
headptr
is uninitialized and could point to anything.
1 2 3 4 5 6 7
node *headptr = NULL;
do
{
int val;
node *headptr;
...
Topic archived. No new replies allowed.