[英]pointers c++ - access violation reading location
输出:访问冲突读取位置0x0093F3DC。
我似乎无法找出问题所在。 head和next指针在各自的构造函数中初始化为null。
class List{
public:
node *head;
List(void) // Constructor
{
head = NULL;
}
void insertNode(int f)
{
node *newNode;
newNode=new node();
newNode->value = f;
newNode->next=head;
head=newNode;
}
void displayList()
{
node *ptr=head;
while (ptr!=NULL)
{
cout<<ptr->value<<endl;
ptr=ptr->next;
}
}
bool search( int val)
{
node *ptr= head;
while (ptr!=NULL)
{
if(ptr->value == val)
{
return true;
}
ptr=ptr->next;
}
return false;
}
};
最有可能的是,最好只声明一个指针,而不是先分配一个Node实例,然后再擦除新分配的内存(例如,导致内存泄漏)。 例如:
bool search( int val)
{
//
// Declare the pointer to traverse the data container, assign to the head
// This works only if head is valid. It is assumed that head is pointing
// to valid memory by the constructor and/or other class member functions.
//
node *ptr = this->head;
while (ptr!=NULL)
{
if(ptr->value == val)
{
return true;
}
ptr=ptr->next;
}
return false;
}
在上面的类实现详细信息中,内部头指针始终分配给InsertNode内部的newNode内存。 因此,每次调用InsertNode时磁头都会移动。 这是所需的功能吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.