繁体   English   中英

链表空指针错误 C++

[英]linked list null pointer error c++

我有一个项目要从文件中计算。 由于这是一个学校项目,我不允许使用大多数图书馆,但只能使用基本图书馆。 因此我决定使用哈希映射。 但是我的链表给出了一个空指针异常。 准确地说是“抛出异常:读取访问冲突。是 0xCCCCCCCC。发生了”。 我搜索了很多以找到解决方案,但我找不到任何东西。 感谢您的时间。

public: liste() {
        head = NULL;
        tail = NULL;
    }

    void createnode(string value) {
        liste();
        node* temp = new node;
        temp->data = value;
        temp->next = NULL;

        if (head == NULL) { // get error here!!!!

            head = temp;
            tail = temp;
            temp = NULL;
        }

        else {
            tail->next = temp;
            temp = tail;
        }
    }

        int main()
    {   
        struct site {
            int count;
            string name;
        };  
        unsigned long int i=0;
        unsigned int x=0;
        ifstream theFile("access_log");
        string word;
        liste* table[100000];
        site list[10];

        while (theFile >> word) {   
            if (word.find(".")!=-1) {
                if (word.find("H") == -1) {
                    x=(int)hashG(word);
                    if (x < 100000) {                   
                        table[x]->createnode(word);
                    }
                }
            }

        }
        for (int i = 0; i < 100000; i++) {
            cout << table[i]->length() << "   " << table[i]->getData() << endl;
        }   
        return 0;
    }

在这里,您创建了一个包含 10000 个列表指针的数组

liste* table[100000];

但你永远不会为它们创建任何 liste 对象指向。 以后要调用成员函数

table[x]->createnode(word);

由于您在表中的指针仍未初始化,您的呼叫崩溃了。

我的假设是你想让table成为一个 liste 对象的数组

liste table[100000];

我仍然不明白的是为什么在createNode函数中调用liste() (构造函数?)。

显然没有初始化你的类数组会导致这个。添加这个修复了它。

for ( i = 0; i < 100000; i++)
        {
            table[i] = new liste;

        }

自我注意:如果他们在船上讲述,请不要观看有关代码实现的教程。 人们可能会忘记一些事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM