【发布时间】:2020-06-07 19:54:36
【问题描述】:
首先,如果我的解释不好,我想道歉,英语不是我的第一语言。如果您不理解我在这里写的内容,我很乐意尝试更好地解释。
我正在尝试解决this problem。我有一个结构数组(车间),它是另一个结构(Available_Workshops)的成员。我的问题是,数组中 Workshop 结构的所有实例的所有数据成员在 CalculateMaxWorkshops 函数中的 for 循环的第一次迭代后被清除,从而导致第一次循环后出现分段错误。我尝试使用向量和动态数组,但问题仍然存在。
这是我的代码。
#include <iostream>
using namespace std;
struct Workshop
{
int start = 0;
int dur = 0;
int end = 0;
};
struct Available_Workshops
{
int n = 0;
Workshop *arr = new Workshop[n];
};
Available_Workshops* initialize(int s[], int d[], int n)
{
Available_Workshops aw;
Available_Workshops *u;
aw.n = n;
for (int i = 0 ; i < n ; i++)
{
Workshop w;
w.start = s[i];
w.dur = d[i];
w.end = w.start + w.end;
cout << w.end;
aw.arr[i] = w;
}
u = &aw;
return u;
};
int CalculateMaxWorkshops(Available_Workshops *time_table)
{
int n = time_table-> n, //number of workshop objects
int current_class, next_class=0;
int max_classes = 0;
for (int i = 0 ; i < n-1 ; i++)
{
Workshop cur = time_table -> arr[i];
current_class = cur.end; //all struct members gets cleared for some reason after this line
}
}
我只能编辑上面的,下面的代码被锁定在站点编辑器中。
int main() {
int n; // number of workshops
cin >> n;
// create arrays of unknown size n
int* start_time = new int[n];
int* duration = new int[n];
for(int i=0; i < n; i++){
cin >> start_time[i];
}
for(int i = 0; i < n; i++){
cin >> duration[i];
}
Available_Workshops * ptr;
ptr = initialize(start_time,duration, n);
cout << CalculateMaxWorkshops(ptr) << endl;
return 0;
}
我在 CalculateMaxWorkshops 函数中尝试了不同的方法,但它导致了不同的问题。
int CalculateMaxWorkshops(Available_Workshops *time_table)
{
int n = time_table -> n, //number of workshop objects
int current_class, next_class=0;
int max_classes = 0;
for (int i = 0 ; i < n-1 ; i++)
{
Workshop *cur = &(time_table -> arr[i]);
current_class = cur -> end;
}
}
这次的问题是数组向后“偏移”。换句话说,存储在 arr[i] 中的数据被存储在 arr[i-1] 中,并且在 arr[n-i-1] 中的数据被重新初始化。
总而言之,第一个问题是数据变为 NULL,而第二个问题是数据向后偏移并重新初始化,例如 start = -17891602。
【问题讨论】: