DavidRC
DavidRC

Reputation: 103

C Programming Issues: Passing, creating, and returning structures in functions.

This function doesn't work and I can't figure out why. It compiles fine and the program seems to run, however upon close examination and debugging I'm discovering that:

newImg->x = b;
newImg->y = a;

Isn't actually working and it's causing problems. I tried copying with newImg=img but that doesn't let me change the values of newImg later. They remain the exact same. I also tried modifying the values of img, then doing newImg, but debugging shows that newImg is getting extreme values.

Here is the structure:

typedef struct
{
     unsigned char grayscale;
} PGMPixel;

typedef struct
{
     int x, y;
     PGMPixel *data;
} PGMImage;

Here is the function:

static PGMImage *rotatePGM(PGMImage *img)
{   
    PGMImage *newImg;


    // Memory allocation for pgm
    newImg = (PGMImage *)malloc(sizeof(PGMImage));
    if (!newImg) 
    {
         fprintf(stderr, "Unable to allocate memory\n");
         exit(1);
    }

    //memory allocation for pixel data
    newImg->data = (PGMPixel*)malloc(newImg->x * newImg->y * sizeof(PGMPixel));
    if (!newImg) 
    {
         fprintf(stderr, "Unable to allocate memory\n");
         exit(1);
    }

    int a = img->x;
    int b = img->y;
    newImg->x = b;
    newImg->y = a;  

    int u = a - 1;
    int v = b - 1;
    int i = 0;
    int j = 0;

    if(newImg)
    {
        for (i = 0; i < a; i++)
        {
            for (j = 0; j < b; j++)
            {
                img->data[(j*a)+(u-i)].grayscale = img->data[(i*b)+j].grayscale;
            }
        }
    }   
    return newImg;
}

I'm using MinGW GCC and windows 8 if that helps.

Upvotes: 0

Views: 175

Answers (2)

simonc
simonc

Reputation: 42185

The line

newImg->data = (PGMPixel*)malloc(newImg->x * newImg->y * sizeof(PGMPixel));

is wrong - it uses newImg->x and newImg->y before they are initialised. You should presumably use the values from img instead

newImg->data = malloc(img->x * img->y * sizeof(PGMPixel));

I've made another small change to that line - you don't need to cast the return from malloc

You also use the wrong PGMPixel instance later in the line

img->data[... = img->data[...

(it should presumably be newImg->data you are assigning to)

Upvotes: 2

user2600366
user2600366

Reputation: 68

newImg->data = (PGMPixel*)malloc(newImg->x * newImg->y * sizeof(PGMPixel));

Here you did not initialize your variables.

Upvotes: 2

Related Questions