"Unhandled exception"/"Access violation writing location" error with referenced array pointers
I'm trying to fill a pointer matrix with values from a text file. It's a double pointer to a simple struct with 2 ints, time and tons.
void get_changes(change** &c){
ifstream file("change_data_time.prn"); //data file, time only, size is the same as tons
string line, var; //string placeholders for the getlines
int i, j; // count variables
int count=0;
while(getline(file, line))
count++; //counting matrix size (matrix is square)
c = new change *[count]; //resize pointers with matrix size
for(i=0; i<count; i++)
c[i] = new change[count];
file.clear();
file.close();
file.open("change_data_time.prn"); //reset data stream to read values
i = 0; //reset counting varia开发者_Python百科bles
j = 0;
while(getline(file, line)){
stringstream sline(line); //getlines only read streams and output to strings
while(getline(sline, var, '\t')){ //separate with tabs
stringstream svar(var);
svar >> c[i][j].time; //BREAKS HERE
j++;
}
i++;
}
}
It breaks when i actually try to add the values to the pointer array and i can't understand why. It breaks on the first run of the while loops.
Thanks in advance for any suggestions.
I would rewrite the code to get rid of the manual memory management around change** c
.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
struct MaxtrixElement
{
double time;
};
std::istream& operator >> (std::istream& in, MaxtrixElement& dest)
{
double d;
// error checking ommitted
in >> d;
dest.time = d;
return in;
}
std::ostream& operator << (std::ostream& os, const MaxtrixElement& e)
{
os << e.time;
return os;
}
typedef std::vector<MaxtrixElement> Line;
typedef std::vector<Line> Matrix;
void foobar(std::istream& is, Matrix& dest)
{
std::string ln;
while(std::getline(is, ln))
{
std::stringstream lnStream(ln);
Line l;
std::copy(std::istream_iterator<MaxtrixElement>(lnStream),
std::istream_iterator<MaxtrixElement>(),
std::back_inserter(l));
dest.push_back(l);
}
}
int main()
{
Matrix m;
foobar(std::cin, m);
for(Matrix::const_iterator it=m.begin(); it!=m.end(); ++it)
{
std::copy(it->begin(), it->end(), std::ostream_iterator<MaxtrixElement>(std::cout, ", "));
std::cout << '\n';
}
}
精彩评论