0
votes

I am trying to implement very simple code of Linked List but unhandled exception error occurred. I want to access 2nd element data from first I have an error in printing it it the visual studio. An exception handling error comes and program stops working.

Error is: 0

Unhandled exception at 0x00105485 in LinkedList.exe: 0xC0000005: Access violation reading location 0x00000000

class Node{
public:
    int data;
    Node *next;

};

int main() {
    Node *p = new Node();
    p->data = 10;
    p->next = NULL;

    Node *q = new Node();
    q->data = 9;
    q->next = NULL;
    //now print this
 p->next->data 
    system("pause");

}
1

1 Answers

0
votes

You are defining p->next = NULL and then trying to read p->next->data. Which means that you are trying to read data from NULL. If you want to create a linked list from your nodes, you need to link them yourself, I.E. do something like this:

Node *p = new Node();
p->data = 10;
p->next = NULL;

Node *q = new Node();
q->data = 9;
q->next = NULL;

p->next = q;  // Link the two nodes

//now print this
std::cout << p->next->data;
system("pause");