代码之家  ›  专栏  ›  技术社区  ›  ibrahim

“main”已停止工作-C++[开发人员++]

  •  -3
  • ibrahim  · 技术社区  · 7 年前

    我的代码表现得很奇怪。它有时工作,有时崩溃。

    当它崩溃时,它会说:

    一个问题导致程序停止正常工作

    我的 main :

    int main() {
        start();
        Read();
    
        cout << "Enter the code of the course: ";
        cin >> coursecode;
        cout << "\n1111111\n";
        searchCourse(coursecode);
        cout << "\n222222\n";
    
        return 0;
    }
    

    我在searchCourse函数的上方和下方写了两行代码,以查看程序是否编译了所有行。它确实编译了所有内容,最后它会在崩溃之前打印222222。

    start方法只创建一个二进制树对象数组,然后存储 根据课程,学生数据(从文本文件中读取)。

    开始():

    BinaryTree *a[10];
    
    void start()
    {
        for(int g=1;g<=10;g++)
        {
            a[g] = new BinaryTree(g);
        }
    }
    

    searchCourse():

    void searchCourse(string code)
    {
        for(int j=1;j<=count;j++)
        {
            if(a[j]->checkit(code)!=0)
            {
                a[j]->display();
    
                break;
            }
        }
    }
    

    BinaryTree中的Checkit()。h:

    bool checkit(string m)
    {
        if (root==NULL)
            return false;
        else
            if(root->data.getCourse()==m)
                return true;
            else
                return false;
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   pepperjack    7 年前
    BinaryTree *a[10];
    for(int g=1;g<=10;g++)
    {
        a[g] = new BinaryTree(g);
    }
    

    将出现内存异常。您有一个10的数组,并且您正在尝试访问第11个元素(自 g<=10 a[10] 是第十一个元素)。使用:

    for(int g=0;g<10;g++)
    

    相反你可能也必须这样做 new BinaryTree(g+1); 如果二叉树从1开始。

    这也是代码中其他地方的错误,如 for(int j=1;j<=count;j++) ( for(int j=0;j<count;j++) 可能是你想要的)。

    数组从0开始。 Why does the indexing start with zero in 'C'?