somerandomdude
somerandomdude

Reputation: 337

Having trouble printing value of struct member

I have data structure I'm using for a linked list but I can't print the value of each node. I just get exited with non-zero status. Here's the code:

#include <iostream>

using namespace std;

 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };


 int main()
 {
   ListNode* l1;
   l1->val = 1;

   cout << l1->val << endl;

   return 0;
 }

Upvotes: 0

Views: 192

Answers (1)

jiakai
jiakai

Reputation: 501

l1 is an uninitialized pointer; before using a pointer, you have to point it to a valid object:

#include <iostream>                                                          

using namespace std;                                                         

struct ListNode {                                                            
    int val;                                                                 
    ListNode *next;                                                          
    ListNode(int x) : val(x), next(NULL) {}                                  
};                                                                           


int main()                                                                   
{                                                                            
    ListNode* l1 = new ListNode(0);  // allocate memory                      
    l1->val = 1;                                                             

    cout << l1->val << endl;                                                 

    delete l1;  // deallocate memory                                         

    return 0;                                                                
}       

Upvotes: 3

Related Questions