Dynamic array crashes program
May 16, 2015 at 4:03am May 16, 2015 at 4:03am UTC
I am attempting to write a library that loads a map. I load a file, and set its contents to a dynamic array. When I print the X and Y position of the for loops, the array cannot seem to get past (0,2). I am using the TDM compiler. The program becomes unresponsive, and must be closed out of. I have tried a vector of character vectors as well, again, same problem.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <fstream>
#include <iostream>
#include <exception>
#include <vector>
class map{
public :
char ** objects;
map(std::string location,int x,int y){
objects = new char * [x];
for (int i; i<y; i++){
objects[i]= new char [y];
}
std::ifstream file(location);
if ( !file ){
std::cout << "File not found." ;
system("pause" );
exit( 1 );
}
char ch;
try {
for (int y_pos=0; y_pos<y; y_pos++){
for (int x_pos=0; x_pos<x; x_pos++){
file.get(ch);
std::cout << x_pos;
std::cout << y_pos << std::endl;
objects[x_pos][y_pos]=ch; //When this is commented out, the program does not crash.
}
}
}catch (std::exception& e){
std::cout << e.what();
}
file.close();
}
};
Any help onto how I can fix this would be greatly appreciated.
May 16, 2015 at 5:44am May 16, 2015 at 5:44am UTC
You aren't assigning i to 0.
for (int i; i<y; i++){
Also I would probably use a vector of strings or something similar if you are trying to go the C++ way instead of a double char pointer.
Topic archived. No new replies allowed.