[英]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.