Frage

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.

War es hilfreich?

Lösung

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));

Andere Tipps

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

If you want to use a pointer, you have to allocate enough memory to hold a structure. However, you are trying to dereference a null pointer: this leads to undefined behavior.

#include <stdlib.h>
Image *x = malloc(sizeof *x);

And then you can initialize the members. NB: Use calloc here is non-portable, because a null-pointer is not guaranteed to have a memory representation all-bits-zero.

Anyway, it seems that you don't need to use a pointer here.

#include <stddef.h>
Image x = { 0, 0, 0, NULL };
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top