C Programming Issues: Passing, creating, and returning structures in functions. -
this function doesn't work , can't figure out why. compiles fine , program seems run, upon close examination , debugging i'm discovering that:
newimg->x = b; newimg->y = a; isn't working , it's causing problems. tried copying newimg=img doesn't let me change values of newimg later. remain exact same. tried modifying values of img, doing newimg, debugging shows newimg getting extreme values.
here structure:
typedef struct { unsigned char grayscale; } pgmpixel; typedef struct { int x, y; pgmpixel *data; } pgmimage; here function:
static pgmimage *rotatepgm(pgmimage *img) { pgmimage *newimg; // memory allocation pgm newimg = (pgmimage *)malloc(sizeof(pgmimage)); if (!newimg) { fprintf(stderr, "unable allocate memory\n"); exit(1); } //memory allocation pixel data newimg->data = (pgmpixel*)malloc(newimg->x * newimg->y * sizeof(pgmpixel)); if (!newimg) { fprintf(stderr, "unable allocate memory\n"); exit(1); } int = img->x; int b = img->y; newimg->x = b; newimg->y = a; int u = - 1; int v = b - 1; int = 0; int j = 0; if(newimg) { (i = 0; < a; i++) { (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 , windows 8 if helps.
the line
newimg->data = (pgmpixel*)malloc(newimg->x * newimg->y * sizeof(pgmpixel)); is wrong - uses newimg->x , newimg->y before initialised. should presumably use values img instead
newimg->data = malloc(img->x * img->y * sizeof(pgmpixel)); i've made small change line - you don't need cast return malloc
you use wrong pgmpixel instance later in line
img->data[... = img->data[... (it should presumably newimg->data assigning to)
Comments
Post a Comment