2

I am working on a homework project to rotate a simple 2D array holding RGB values for a PGM file.

I've read many posts in these forums about how to do this in C, and I've almost got it working. My output file has the correct dimensions and is rotated, but there is a thick black border around the top and sides. I just can't figure out what I'm doing wrong.

Any help would be greatly appreciated!

I modified the code presented here to get started, and this is the rotate90 function I'm working on now:

PGMImage* rotate90(PGMImage *old_img)
{
    int x, y;
    PGMImage *new_img = malloc(sizeof(PGMImage));
    new_img->maxVal = old_img->maxVal;
    new_img->width = old_img->height;
    new_img->height = old_img->width;
    for (x = 0; x < old_img->width; x++)
    {
        for (y = 0; y < old_img->height; y++)
        {
            new_img->data[old_img->height - 1 - y][x].r = old_img->data[x][y].r;
            new_img->data[old_img->height - 1 - y][x].g = old_img->data[x][y].g;
            new_img->data[old_img->height - 1 - y][x].b = old_img->data[x][y].b;
        }
    }
    return new_img;
}

void main()
{
    PGMImage* img = malloc(sizeof(PGMImage));
    getPGMfile("columns.pgm", img);
    save("columns_new.ppm", rotate90(img));
}  

The save() and getPGMfile() functions work perfectly on their own.
It's only when I pass the result of my rotate90() function to save() that I get the funky results.

Community
  • 1
  • 1
crgolden
  • 4,332
  • 1
  • 22
  • 40
  • Are you allocating space for the `.data` member array? – luser droog Jul 20 '13 at 11:19
  • Thanks for the question luser droog. The `data` array is allocated at 800 x 800 within the `PGMImage` typedef (in the header file). I'm only working with images of max size 640 x 480. – crgolden Jul 20 '13 at 13:14

1 Answers1

0

How about trying memcpy(new_img, old_img, sizeof(PGMImage) after the malloc statement. Maybe some other attributes besides width and height are not initialized. And also, if the data variable is a pointer, did you malloc a piece of memory for data for the new_img object?

WDan
  • 533
  • 1
  • 4
  • 13
  • Thanks for the suggestion WDan. I added the `memcopy` code you suggested but it didn't change anything - the only attributes `PGMImage` has are `maxVal`, `width`, `height`, and `data` (which is a 2D array of structs holding the `r` `g` and `b` ints). – crgolden Jul 20 '13 at 13:08