Calarax911
Calarax911

Reputation: 35

Problems printing out an array for a ppm file

I am trying to create an array using a struct in order to create a ppm file. I then want to call other functions in order to change the color values (rgb) for each cell to make shapes.

This is as far as I got trying to print out an array with three values for rgb.

bool writeImage(const Color image[][IMAGE_WIDTH], int height) {

    ofstream imgGen;

    imgGen.open("imgGen.txt");

    imgGen << "P3 \n";
    imgGen << IMAGE_WIDTH << " " << height << "\n";
    imgGen << COLOR_SCALE << "\n";

    for (int imageRow = 0; imageRow < height; imageRow++) {
       for (int imageColumn = 0; imageColumn < IMAGE_WIDTH; imageColumn++)
          imgGen << image[imageRow][imageColumn].red << " " << image[imageRow] 
              [imageColumn].green << " " << image[imageRow][imageColumn].blue;
       imgGen << endl;
    }

    imgGen.close();

return 0;
}

and this is the struct I'm trying to use for the array.

struct Color
{
    unsigned char red;
    unsigned char green;
    unsigned char blue;
};

int main()
{
    Color image[IMAGE_HEIGHT][IMAGE_WIDTH];
    image[IMAGE_HEIGHT][IMAGE_WIDTH].red = 0;
    image[IMAGE_HEIGHT][IMAGE_WIDTH].green = 1;
    image[IMAGE_HEIGHT][IMAGE_WIDTH].blue = 2;

    writeImage(image, IMAGE_HEIGHT);

return 0;
}

I have it printing out as a text file to check the formatting and am trying to get it to print out three values per pixel similar to this:

P3
200 300
255

255 0 0 0 0 255
0 255 0 0 0 0

What is wrong with my current approach and what can I be doing differently in my code? Thank you for any assistance!

Upvotes: 2

Views: 214

Answers (1)

R Sahu
R Sahu

Reputation: 206567

The lines

image[IMAGE_HEIGHT][IMAGE_WIDTH].red = 0;
image[IMAGE_HEIGHT][IMAGE_WIDTH].green = 1;
image[IMAGE_HEIGHT][IMAGE_WIDTH].blue = 2;

are wrong on two accounts.

  1. They access the array using out of bounds indices, and hence cause undefined behavior.
  2. They leave the contents of the array still in an uninitialzed state.

You need to set the values of elements of the array one by one, just like you are accessing them to print them.

for (int imageRow = 0; imageRow < IMAGE_HEIGHT; imageRow++)
{
   for (int imageColumn = 0; imageColumn < IMAGE_WIDTH; imageColumn++)
   {
      image[imageRow][imageColumn].red = 0;
      image[imageRow][imageColumn].green = 1;
      image[imageRow][imageColumn].blue = 2;
   }
}

Upvotes: 3

Related Questions