2

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!

Calarax911
  • 35
  • 4
  • Your output for color looks like your is is for `height = 2;` `#define IMAGE_WIDTH 2`, but that would not correlate with your earlier `200 300` output?? (your color output is literally `R B G black` (e.g `ff0000, 0000ff, 00ff00, 000000`)) – David C. Rankin Jan 24 '19 at 06:33

1 Answers1

3

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;
   }
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • I see where I was going wrong, i thought you could initialize all elements like you could with a normal array. Any insight into how I can get it to print out the array? – Calarax911 Jan 24 '19 at 07:55
  • @Calarax911, what's wrong with your posted code? That seems fine to me, – R Sahu Jan 24 '19 at 13:59