0

I'm writing a program to read from a .ppm file and store their values. This code that I wrote worked, but it just crashes (break?) right before closing the file. Can someone please help me find out how to fix this?

        string EndHeader, Red, Green, Blue;

        for(int i=0; i<4; i++)
        {
            readFile >> EndHeader;
            //cout << EndHeader << endl;
        }


        for (int i = 0; i < width * height; i++)
        {
            readFile >> Red;
            r[i]->R = stoi(Red);
            readFile >> Green;
            r[i]->G = stoi(Green);
            readFile >> Blue;
            r[i]->B = stoi(Blue);
            //cout << r[i]->R << " " << r[i]->G << " " << r[i]->B << endl;
        }
        

        readFile.close();

The r comes from this part of the program

struct Pixel
{
    unsigned int R, G, B;
};

class Image
{
private: 

    char magicNum1, magicNum2;
    unsigned int width, height, maxValue;
    Pixel **r;

void alloc_raster()
{
    r = new Pixel*[height]; // allocate pointers to the rows
    for (unsigned int k = 0; k < height; k++) // for all rows
    {
        r[k] = new Pixel[width]; // allocate pixels in row
    }

}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Aimie
  • 1
  • 1
  • 1
    Why not put the pixel data in a vector instead of tempting the cruel hand of fate? – Passerby Dec 06 '21 at 03:44
  • `r` is allocated as `height` pointers pointing to `width` values but in this loop `for (int i = 0; i < width * height; i++)` it is treated as linear values. Pick one or the other. – Retired Ninja Dec 06 '21 at 03:45
  • Either use `std:;vector< std::vector >` or just `std::vector` and sort the indexing as (row,col) -> row*numcols + col –  Dec 06 '21 at 03:46
  • Your array `r` contains `height` elements, each of which is an array of `width` pixels. Your read loop indexes into `r` with `i`, which can be as large as `width * height - 1`, which is a guaranteed mega-overflow. – paddy Dec 06 '21 at 03:46
  • I change the pixel array r to 2d `r[i][j]` and used 2d for loop `for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { readFile >> Red; r[i][j].R = stoi(Red); ... }` like this and it stop crashing. But I should look up on using vector too. Thanks everyone! – Aimie Dec 06 '21 at 05:06

0 Answers0