2

I'm having some issues with a char** with file input. I'm doing a project where we are manipulating PGM files. I'm trying to get the header from the file using a char** but all it does is return null. It will run through the code that I have get the dimensions and return them to the screen but when I try to print the header I just get (null) as my output

//Creation of the char**

char **header=(char**)malloc(2*sizeof(char*));

//File input

FILE * fin;
fin=fopen(argv[1], "rb");
fscanf(fin, "%s", *header);
printf("%s", header[0]);
fclose(fin);

I'm not 100% sure if I'm creating header right or not or if I'm printing header right either. Any help would be much appreciated.

kevorski
  • 816
  • 1
  • 11
  • 29

2 Answers2

2

malloc(2*sizeof(char*)); allocates enough memory for 2 char pointers. That probably won't be enough to hold the header.

Actually, looking at the pgm spec, it appears that 2 chars will hold the 'magic number', but you would still need to allocate 3 chars, so that you could hold the trailing NULL that fscanf will produce.

So try getting rid of one level of indirection:

char *header=malloc(3*sizeof(char));
AShelly
  • 34,686
  • 15
  • 91
  • 152
2
char *header = malloc(2*sizeof(char));
fscanf(fin, "%s", header);

But then 2 characters is very small - would really only work if you did an fread or something that won't exceed the size of the allocated header space you're reading into...or maybe increase the size of "header" so you can fit more in.

Edit - pointer indirection

We use pointers to point at allocated memory - that's what's going on with *header = malloc.... We also use pointers to pass arguments to functions that we wish to alter the value of, which is why if you are to allocated a char * inside another function and have the caller know about it you need to use a pointer to a pointer: char **.

noelicus
  • 14,468
  • 3
  • 92
  • 111
  • the function that calls header has to be a ** `int ** pgmRead( char **header, int *numRows, int *numCols )` this is the prototype of the first function. would making a char* be able to be passed into the function? – kevorski Nov 19 '13 at 19:36
  • use the `**header` argument to return the memory you allocated: `char* myheader = malloc(...); *header = myheader;` – AShelly Nov 19 '13 at 19:41