链表自制类哭诉内存访问问题(C++)

Linked list homemade class cryes about memory access troubles (C++)

本文关键字:问题 访问 C++ 内存 链表      更新时间:2023-10-16

在Visual Studio 2013中构建项目时,会显示以下消息:prj.exe中0x00CD5154处未处理的异常:0xC0000005:写入位置0x00000004时发生访问冲突请帮忙。这实际上是一个例子https://www.youtube.com/watch?v=3gZ7F31Mwi0我写的几乎一样。

收割台.h

#ifndef HEADER_H_
#define HEADER_H_
#include <iostream>
#include <string>
//#include <iostream>
//#include <vector>
typedef struct Node
{
    int data;
    Node* link;
}* NodePtr;
class List
{
public:
    List();
    ~List();
    int numberOfElements();
    NodePtr getPointer(const int node_number) const;
    void addNode(int data_);
    //NodePtr head;
private:

    NodePtr head;
    NodePtr curr;
    NodePtr temp;
    NodePtr start_index;
};
#endif // !HEADER_H_

来源.cpp

   #include "Header.h"    
    List::List()
    {
        head = NULL;
        curr = NULL;
        temp = NULL;//head_ptr = this->Nodes;
        start_index = NULL;
    }
    List::~List()
    {
    }
    int List::numberOfElements() 
    {
        size_t i = 0;
        temp = start_index;
        while (temp->link != NULL)
        {
            temp = temp->link;
            i++;
        }
        return i;
    }
    NodePtr List::getPointer(const int node_number) const
    {   
        NodePtr counter = start_index;
        for (size_t i = 0; i < node_number; i++)
        {
    //%
            std::cout <<  i << std::endl;
    //%
            if (counter == NULL)
            {
                std::cout << "last index is " << i << std::endl;
                return counter;
            }
            counter = counter->link;
        }
        return counter;
    }
    void List::addNode(int data_)
    {
        NodePtr n = new Node;
        n->data = data_;
        n->link = NULL;
        if (head != NULL)
        {
            curr = head;
            while (curr != NULL)
                curr = curr->link;
            curr->link = n;
        }
        else
        {
            head = n;
            start_index = n;
        }
    }

main.cpp

  #include "Header.h"
    int main()
    {
        using namespace std;
        List one;
        one.addNode(1);
        one.addNode(2);
        one.addNode(3);
        //cout << (*one.head).data << endl;
        //cout << one.getPointer(1)->data << endl;
        cin.get();
    }

循环之后

while (curr != NULL)
    curr = curr->link;

curr将是NULL(想想这个,直到你意识到为什么它是真的)。

因此,线路

curr->link = n;

取消引用空指针的位置无效。

你想要

while (curr->link != NULL)
    curr = curr->link;