首页 > 解决方案 > 尝试用 C++ 编写我自己的链表实现,在列表中点击 3 个元素后出现代码段错误

问题描述

我一直在尝试编写自己的链表实现,但是当我尝试访问第三个元素或它之后的任何内容时,代码会出现段错误。添加元素不会出现段错误,但访问会。我在 get() 函数中找不到指针错误。

列表中的每个节点都存储(模板 t 的)数据和指向下一个节点的指针。我对所有东西都有两个功能——一个用于第一个元素,一个用于任何后续元素。后续元素的 get() 函数始终存在段错误。我在函数中有一些调试消息会吐出我无法解释的结果。例如,如果我对第二个元素(然后是第三个元素)运行 get() 请求,则代码不会出现段错误,但它确实返回了明显不正确的结果。我放置的调试消息表明,当第二个元素调用函数检查第三个元素时,会发生段错误,如果它发生的话。尝试使用和不使用 cout << newList.get(2) << endl; 行的代码 你会得到非常不同的结果。

一个可能的原因是指针存储 - 我让 get() 函数在循环时输出每个元素(第一个元素除外)的指针,并将它们与 add() 函数输出的指针和元素的指针进行比较0 和 1 匹配,但 2 及以上不匹配,我似乎无法弄清楚为什么会这样。

#include <iostream>
using namespace std;



template <class T> class myLinkedList{
T data;
myLinkedList<T> *next = NULL;

public:
    myLinkedList(T input){
        data = input;

    }
    void add(T input){
        if(next == NULL){
            myLinkedList<T> newItem(input);
            next = &newItem;
            cout << "adding to list, data is " << input << ", pointer is " << next << endl;
        }else{
            myLinkedList<T> nextEntry = *next;
            nextEntry.add(input);
        }
    }


    T getData(){
        return data;
    }
    //the start  of the get function, only used by the first entry in the list
    T get(int entry){
        int currentPosition = 0;
        if(entry == currentPosition){
            return getData();
        }else{
            //defrefrence the pointer anc check the next entry
            myLinkedList<T> nextEntry = *next;
           return nextEntry.get(entry, ++currentPosition);
        }
    }

private:
    //this vesion is the hidden, private vesion only used by nodes other than the first one
    //used to keep track of position in the list
    T get(int entry, int currentPosition){
        //cout << currentPosition << endl;
        if(entry == currentPosition){
            return data;
        }else{
            //derefrence the pointer and check the next entry
            cout << next << endl;
            myLinkedList<T> nextEntry = *next;
            currentPosition++;
           T output = nextEntry.get(entry, currentPosition);
           return output;
        }

    }


};
int main(){
myLinkedList<int> newList(3);
newList.add(4);
newList.add(5);
newList.add(7);
newList.add(9);
cout << newList.get(2) << endl;
cout << newList.get(3) << endl;
return 0;
}

结果显然是错误的——程序应该吐出两组指针,以及数字 5 和 7(列表元素)

标签: c++pointers

解决方案


您的主要问题之一在这里:

if(next == NULL){
    myLinkedList<T> newItem(input); // <<<<<<<<<<<<<
    next = &newItem;
    cout << "adding to list, data is " << input << ", pointer is " << next << endl;
}

if您在范围内的堆栈上分配一个项目。然后你让next指向这个项目。但是......项目的生命周期受此范围的限制。当您退出范围时,此项目不再存在。您需要通过“新”或其他方法动态分配它。


推荐阅读