2

I am currently writing a program for an assignment that requires a single black line to be drawn perfectly solid diagonal (so that all x=y) from the upper-left corner of a standard PNM P6 file. I have had no issues with file I/O.

However, I cannot get the diagonal line to display properly. Instead of the single, solid, white line I need from the corner, I get dotted lines wrapping over the image as shown in this picture.

Does anyone have any idea as to what is going wrong?

My function is as follows:

Image *
DiagonalWhite(Image *img)
{
    int i, j;

    for (i = 0; i < img->x; i++)
    {
        for (j=0; j < img->y; j++)
        {
            if (i==j)
            {
                img->data[i*img->y+j].red=255;
                img->data[i*img->y+j].green=255;
                img->data[i*img->y+j].blue=255;
            }
        }   
    }

    return img; 
}

1 Answers1

1

You don't give any definition for Image *img, so actually this question cannot be answered with confidence; however, I assume you are doing the same class as yesterday's Issues writing PNM P6.

You are multiplying in the wrong direction. img->y holds the height of the image. However, since you need the span, you should be using img->x -- the width -- to go down by i pixels (followed by adding j pixels to go right).

img->data[i*img->x+j].red=255; /* x, not y */

Note: Better names for these properties would have been width and height.

Note: It's easier and quicker to loop only once over the minimum of width and height, and set pixel[i,j] immediately, rather than testing which one 'has' the same x and y position.

Community
  • 1
  • 1
Jongware
  • 22,200
  • 8
  • 54
  • 100