V
vaneric001
hi
I am a newbie to c coding and going thru K&R ...
i have a structure to represent an image as
struct image{
char* imagename;
int imagewidth;
int imageheight;
long* pixels;
};
typedef struct image img;
typedef img* imgptr;
here long * pixels shd point to an array of long values representing
pixels of the image.Arraysize (ie number of pixels )will be known only
at runtime.i want to read values into this struct and return a pointer
so i can use this later in another fn
so i wrote
imgptr readimage(char* filename){
/* read image with some library and set wifth,height and get
pixel data array (obtained like long* pixeldata)*/
....
/* allocate memory for structure */
imgptr thisimageptr=malloc(sizeof(thisimageptr));
if(thisimageptr==NULL) exit(EXIT_FAILURE);
int numberofpixels=width * height;
/*allocate memory for the long * pixels */
thisimageptr->pixels=malloc(sizeof(long*) * numberofpixels);
if(thisimageptr->pixels==NULL) exit(EXIT_FAILURE);
/* set fields of struct */
thisimageptr->imagename=filename;
thisimageptr->imagewidth=width;
thisimageptr->imageheight=height;
for(i=0;i<numberofpixels;i++){
thisimageptr->pixels=pixeldata;;
}
return thisimageptr;
}
if another fn gets this pointer it should be able to retrieve the
fields and should be able to iterate over the pixelvalues
i am a little doubtful about the malloc part..is the above mallocs
correct ? or is there some hidden risk?
I am a newbie to c coding and going thru K&R ...
i have a structure to represent an image as
struct image{
char* imagename;
int imagewidth;
int imageheight;
long* pixels;
};
typedef struct image img;
typedef img* imgptr;
here long * pixels shd point to an array of long values representing
pixels of the image.Arraysize (ie number of pixels )will be known only
at runtime.i want to read values into this struct and return a pointer
so i can use this later in another fn
so i wrote
imgptr readimage(char* filename){
/* read image with some library and set wifth,height and get
pixel data array (obtained like long* pixeldata)*/
....
/* allocate memory for structure */
imgptr thisimageptr=malloc(sizeof(thisimageptr));
if(thisimageptr==NULL) exit(EXIT_FAILURE);
int numberofpixels=width * height;
/*allocate memory for the long * pixels */
thisimageptr->pixels=malloc(sizeof(long*) * numberofpixels);
if(thisimageptr->pixels==NULL) exit(EXIT_FAILURE);
/* set fields of struct */
thisimageptr->imagename=filename;
thisimageptr->imagewidth=width;
thisimageptr->imageheight=height;
for(i=0;i<numberofpixels;i++){
thisimageptr->pixels=pixeldata;;
}
return thisimageptr;
}
if another fn gets this pointer it should be able to retrieve the
fields and should be able to iterate over the pixelvalues
i am a little doubtful about the malloc part..is the above mallocs
correct ? or is there some hidden risk?