Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize structure in main function

I am trying to write simple pgm file reading C program. I had to create simple structure:

typedef struct pgmImage {
   int R; //rows
   int C; //collumns
   int G; //grey scale
   int **pix;  // array of pixels
}Image;

Now i have to initialize empty Image structure.I need one to set all variables based on *.pgm file in other function. All the time i am getting "unable to read memory" and 'unitialized local variable x used'. I have tried to simply do :

Image *x=0;

but program crashes when read function try to set R,C,G values.

like image 295
Norrec Avatar asked Aug 13 '26 01:08

Norrec


2 Answers

If you want a pointer to Image you have to initialize like this.

Image *x = NULL;

Accessing the image (x) camps like this :

x-> C = 0;
x-> ...
x->pix = NULL;

But first you need to allocate memory to your image.

x = (Image*) malloc(sizeof(Image));
like image 122
dreamcrash Avatar answered Aug 14 '26 16:08

dreamcrash


Image x = {0}

it s a static memory allocation of image element x

or

Image *x = calloc(1,(sizeof(Image));

it s a dynamic memory allocation of image and x is a pointer to the allocated memory

the calloc will allocate emory and initiate all memory to 0, so the pointer in the structure will be initiated systematically to NULL

like image 37
MOHAMED Avatar answered Aug 14 '26 14:08

MOHAMED



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!