简体   繁体   中英

Why doesn't NULL pointer work?

here's my code

class LList{
struct Elem{int data;Elem *next;};     
Elem *head;
public:


void Push(int dat){
  if(head==NULL){
    head=new Elem;
    head->data=dat;
    head->next=NULL;
  } else {
    // ......
  }
}

But when i use it, it doesn't work. The problem is it never finds the pointer to be NULL and it should me NULL. Even when I assigning NULL to the pointer in constructor it doesn't work. Visual Studio gives me error that says I cannot access desired memory location.

Simply initialize head in the ctor and it should work.

class LList{
  //...
  LList() : head(0) {} // or head(NULL) if you prefer
  // ...
};

Note: IIRC it is considered equally bad style comparing with == NULL as for example == TRUE ... the better (in my not so humble opinion) style is if(!head) , but that is cosmetics. So just a note.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM