I have meet a problem that i cant debug my code. it keep showing me that unhandled exception.
#include <iostream>
#include <stdlib.h>
#include <ctime>
#define max 10
using namespace std;
struct Node{
int data;
Node *next;
};
void initNode(Node *tmpHead, int n){
tmpHead->data =n;
tmpHead->next =NULL;
}
void displayNodes(Node *cur) {
cout <<"Data is";
while(cur){
cout<< cur -> data << " ";
cur = cur->next;
}
cout << " *\n" <<endl;
}
void addNodes(Node * cur, int n){
Node *newNode = new Node;
newNode-> data = n;
newNode-> next = NULL;
while( cur -> next){
cur = cur -> next;
}
cur -> next = newNode;
}
int countTotalNodes(Node *cur){
int count =0;
while(cur){
count++;
cur = cur->next;
}
return count;
}
void main () {
srand(time(NULL));
Node* head = new Node;
int i =0;
int j= 0;
initNode ( head, rand() %100);
for ( int i = 0; i<max-1; i++)
addNodes( head, rand() % 100);
cout << endl;
cout << "Entered array is: " << endl;
displayNodes( head);
Node* array[max];
Node* cur= head;
Node* k;
for( int j = 0; j<max ; j++)
{
array[i] = cur;
cur = cur->next;
}
for (int i=0; i<max-1; i++) //sorting
{
for(int j=0; j<max-i-1; j++)
{
if(array[j]->data > array[j+1]->data)
{
k = array[j];
array[j] = array [j+1];
array[j+1] = k;
}
}
}
head = array[0];
for (int i =0; i<max -1; i++)
array[i]->next = array[i+1];
array[max-1]->next = NULL;
cout <<"Sorted Array is: " <<endl;
displayNodes( head);
}
I have found the part which i cant run it
if(array[j]->data > array[j+1]->data)
i tried to retype it and it still giving me the same error. tried a few different pc it giving me the same error or it crashed.
Your code says:
for( int j = 0; j<max ; j++)
{
array[i] = cur;
cur = cur->next;
}
But using i as the index to the array makes no sense because j is the loop variable so the array contains random pointers because it isn't initialized properly.
You should run you code in a debugger like I just did and step through the program and watch what it does - it makes finding these things much easier.