【问题标题】:"Process terminated with status -1073741819" simple program with vector“进程以状态-1073741819终止”带有矢量的简单程序
【发布时间】:2015-04-02 08:35:00
【问题描述】:

由于某种原因,每当我运行我的程序时,我都会收到“进程以状态 -1073741819 终止”错误,我读到有些人因为代码块/编译器出现问题而收到此错误,我只是想在我重新安装编译器等之前知道我的代码是否有任何问题。我正在使用 code::blocks 和 GNU GCC 编译器。

我的代码创建了一个向量,该向量存储一周内 40 个工作时间,并在该向量内创建一个向量,该向量存储代表这些小时内可用的 5 人的字母。

Schedule.cpp:

#include <iostream>
#include "Schedule.h"
#include <vector>
#include <string>

using namespace std;

/// Creates a Vector which holds 40 items (each hour in the week)
/// each item has 5 values ( J A P M K or X, will intialize as J A P M K)

vector< vector<string> > week(40, vector<string> (5));

Schedule::Schedule(){
        for (int i = 0; i<40; i++){
            week[i][0] = 'J';
            week[i][1] = 'A';
            week[i][2] = 'P';
            week[i][3] = 'M';
            week[i][4] = 'K';
        }
        // test 
        cout << week[1][3] << endl;
    }

头文件:

#ifndef SCHEDULE_H
#define SCHEDULE_H
#include <vector>
#include <string>

using namespace std;

class Schedule
{
    public:
        Schedule();
    protected:
    private:
        vector< vector<string> > week;

};

#endif // SCHEDULE_H

ma​​in.cpp:

#include <iostream>
#include "Schedule.h"
#include <vector>
#include <string>

using namespace std;

int main()
{
    Schedule theWeek;
}

【问题讨论】:

  • 使用 GDB 并运行它,然后使用回溯。
  • vector&lt; vector&lt;string&gt; &gt; week(40, vector&lt;string&gt; (5)); - 这将创建一个名为 week 的全局矩阵变量(不要与 Schedule::week 混淆)。这是故意的吗?我假设您要在构造函数中初始化成员变量;如果是这样,您应该在构造函数中写入this-&gt;week,或者删除/重命名全局变量声明,或者将全局声明放在命名空间中。

标签: c++ vector compiler-errors codeblocks


【解决方案1】:

这不是编译器错误。

您的构造函数出现内存错误。

您的代码有几处问题,例如在您的 cpp 中,您声明了一个全局向量周,然后将其隐藏在构造函数中,因为构造函数将访问 Schedule::week。

你的 cpp 应该是这样的:

// comment out the global declaration of a vector week ...
// you want a vector for each object instantiation, not a shared vector between all Schedule objects
// vector< vector<string> > week(40, vector<string> (5)); 


Schedule::Schedule()
{
    for (int i=0;i<40;i++)
    {
        vector<string> stringValues;
        stringValues.push_back("J");
        stringValues.push_back("A");
        stringValues.push_back("P");
        stringValues.push_back("M");
        stringValues.push_back("K");
        week.push_back(stringValues);
    }
}

当您第一次尝试访问您的周向量时,您的代码中出现了内存错误:

 week[i][0] = 'J' ;

在你调用那行代码的那一刻,你的 Schedule::week 向量里面有 0 个元素(所以 week[i] 已经是一个错误)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-26
    • 2017-03-26
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    相关资源
    最近更新 更多