I'm not sure exactly what is causing this error, as the code was working for a little while, but I must've changed something that messed it up and I've never been able to get it working again.
This is the data in the text file being loaded into the 2d array:
10 8 0 255 255 255 0 0 255 255 255 0 255 0 255 255 0 0 255 255 0 255 255 255 0 255 255 255 255 0 255 255 255 255 255 0 255 255 0 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 0 255 255 0 255 255 255 0 0 0 255 255 255 255 0 0 0
10/8
being the length/height of the array. imagecorrupted.txt
is the same as above, but it has a 355
instead of a 255
somewhere in the data.
This is the relevant code I've come up with so far:
int** load(string imageFile, int &length, int &height) {
ifstream file(imageFile);
if(file.is_open()) {
file >> length; // Loads 10 into length
file >> height; // Loads 8 into height
int** array = new int*[height];
for(int i = 0; i < height; i++) {
array[i] = new int[length];
}
for(int i = 0; i < height; i++) {
for(int j = 0; j < length; j++) {
file >> array[i][j];
if(array[i][j] > 255 || array[i][j] < 0) {
cout << "Image is corrupted." << endl;
file.close();
return nullptr;
}
}
}
file.close();
return array;
}
else {
cout << "Unable to open file." << endl;
return nullptr;
}
}
void show(int **image, int length, int height) {
cout << "The height of the matrix is: " << height << endl;
cout << "The length of the matrix is: " << length << endl;
cout << "The matrix is: " << endl;
for(int i = 0; i < height; i++) {
for(int j = 0; j < length; j++) {
cout << " " << image[i][j];
}
cout << endl;
}
}
void invert(int **image, int length, int height) {
for(int i = 0; i < height; i++) {
for(int j = 0; j < length; j++) {
if(image[i][j] == 255) {
image[i][j] = 0;
}
else {
image[i][j] = 255;
}
}
cout << endl;
}
}
void free(int **image, int &length, int &height) {
if(image) {
for(int i = 0; i < height; i++) {
if(image[i]) {
delete[] image[i];
}
}
delete[] image;
}
}
int main() {
int height = 0;
int length = 0;
int** image = 0;
image = load("../resource/imagecorrupted.txt", length, height);
image = load("../resource/image.txt", length, height);
show(image, length, height);
invert(image, length, height);
show(image length, height);
free(image, length, height);
}
Output:
Image is corrupted. The height of the matrix is: 8 The length of the matrix is: 10 The matrix is: 0 255 255 255 0 0 255 255 255 0 255 0 255 255 0 0 255 255 0 255 255 255 0 255 255 255 255 0 255 255 255 255 255 0 255 255 0 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 0 255 255 0 255 255 255 0 0 0 255 255 255 255 0 0 0 // bunch of whitespace -bash: line x: xxxxx Segemntation fault
I should add that this is an assignment from class, so there are certain things I'm restricted in doing (Ex. needs to be 2d array instead of vectors).