每當我到達代碼中的這一點時,我都會收到一個BadPtr錯誤:爲什麼?<BadPtr>迴路上的錯誤
for(int i = 0; i < processTable.size(); i++)
{
data_entry test = *processTable.at(i).dataCurrent; //ERROR
cout << test.text << "\n";
}
這裏是我的代碼:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
enum process_state { READY, RUNNING, WAITING };
struct data_entry {
const char * text;
int time;
};
struct process_entry
{
int process;
const data_entry * dataStart;
const data_entry * dataEnd;
const data_entry * dataCurrent;
process_state state;
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<data_entry> dataTable;
vector<process_entry> processTable;
string line;
ifstream myfile ("C:\\Users\\1162852\\Documents\\visual studio 2010\\Projects\\Project 1 (OS)\\Debug\\input.txt");
if (myfile.is_open())
{
int processAmount = 0;
while (getline (myfile,line))
{
if(line.find("START") != string::npos)
{
data_entry newEntry;
newEntry.text = "START";
newEntry.time = atoi(line.substr(6, 6).c_str());
dataTable.push_back(newEntry);
process_entry newProcessEntry;
newProcessEntry.dataStart = &dataTable.at(dataTable.size() - 1);
newProcessEntry.dataCurrent = &dataTable.at(dataTable.size() - 1);
newProcessEntry.process = processAmount;
processTable.push_back(newProcessEntry);
processAmount += 1;
}
else if(line.find("END") != string::npos)
{
data_entry newEntry;
newEntry.text = "END";
newEntry.time = NULL;
dataTable.push_back(newEntry);
processTable.at(processTable.size() - 1).dataEnd = &dataTable.at(dataTable.size() - 1);
}
else if(line.find("RUN") != string::npos)
{
data_entry newEntry;
newEntry.text = "RUN";
newEntry.time = atoi(line.substr(4, 4).c_str());
dataTable.push_back(newEntry);
}
else if(line.find("INPUT") != string::npos)
{
data_entry newEntry;
newEntry.text = "INPUT";
newEntry.time = atoi(line.substr(6, 6).c_str());
dataTable.push_back(newEntry);
}
else if(line.find("SSD") != string::npos)
{
data_entry newEntry;
newEntry.text = "SSD";
newEntry.time = atoi(line.substr(4, 4).c_str());
dataTable.push_back(newEntry);
}
}
//reverse(dataTable.begin(),dataTable.end());
/*for(int i = 0; i < dataTable.size(); i++)
{
cout << dataTable.at(i).text << "\n";
}*/
for(int i = 0; i < processTable.size(); i++)
{
data_entry test = *processTable.at(i).dataCurrent;
cout << test.text << "\n";
}
myfile.close();
}
int test;
cin >> test;
return 0;
}
請在編譯時給出** EXACT **錯誤。 – Avery3R
向矢量添加元素時,指向矢量中某個元素的指針變爲* invalid *。看看shared_ptr <>可以做什麼。 –
@Hans是對的,問題是你正在保存一個指向'dataTable'元素的指針,但是如果向量被調整大小,'push_back'會使這些指針無效。考慮將'dataTable'和'processTable'作爲共享指針的向量,以免它們移動。 – Rastaban