Linked List Simple Code eexception handling error comes and program fails

0

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");

}
c++
linked-list
asked on Stack Overflow Feb 24, 2020 by Syed Talal Musharraf • edited Feb 24, 2020 by Arnie97

1 Answer

0

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");
answered on Stack Overflow Feb 24, 2020 by gambinaattori

User contributions licensed under CC BY-SA 3.0