3

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.

Nocturno
  • 9,579
  • 5
  • 31
  • 39
Norrec
  • 37
  • 4

3 Answers3

1
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

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • This utilisation of `calloc` with null pointers is not portable. – md5 Nov 10 '12 at 17:37
  • this because **pix is a double pointer ? this what you mean ? – MOHAMED Nov 10 '12 at 17:41
  • `calloc` sets all bit to zero, but `NULL` does not have necessarily such representation. http://stackoverflow.com/a/5857706/1126268 – md5 Nov 10 '12 at 17:43
  • @Kirilenko I checked some stdlib.h and the NULL macro is defined as 0 please check the following links http://www.mers.byu.edu/docs/standardC/stdlib.html http://trac.assembla.com/chdk/browser/trunk/include/stdlib.h?order=name – MOHAMED Nov 10 '12 at 18:30
1

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));
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
0

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 };
md5
  • 23,373
  • 3
  • 44
  • 93