[英]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. 问题是它永远找不到指针为NULL,而我应该为NULL。 Even when I assigning NULL to the pointer in constructor it doesn't work. 即使我在构造函数中为指针分配NULL也不起作用。 Visual Studio gives me error that says I cannot access desired memory location. Visual Studio给我错误,提示我无法访问所需的内存位置。
Simply initialize head
in the ctor and it should work. 只需在ctor中初始化head
就可以了。
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. 注意: IIRC与== NULL
相比被认为是同样糟糕的样式,例如== TRUE
... if(!head)
样式(在我看来不是很卑鄙)越好,但这就是化妆品。 So just a note. 因此,请注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.