imre
imre

Reputation: 489

Fscanf into a structure

I'm trying to fscanf some data into a struct, the compiler is OK with the code but when I try to print it, it doesn't even print the text. This is the code:

#include <stdio.h>
#include <stdlib.h>

typedef struct xy {
    unsigned x;
    unsigned y;
} myStruct;

int main(void)
{
    FILE *myFile;
    myStruct *xy;
    myFile = fopen("filename.txt", "rb");

    if(fscanf(myFile, "%u %u", &xy->x, &xy->y) != 2)
        fprintf(stderr, "Error!"); exit(1);

    fclose(myFile);
    printf("x: %u, y: %u\n", xy->x, xy->y);
    return 0;
}

Do I need to allocate space for this? If I have to, could you please show me how to go about doing that?

Upvotes: 1

Views: 1432

Answers (1)

Jean
Jean

Reputation: 368

Your do not have a structure there. Simply a pointer on a structure. You can either allocate memory for it with malloc() or declare the structure localy :

myStruct xy;

There is no need to use malloc in this example.

Fixed :

#include <stdio.h>
#include <stdlib.h>

typedef struct xy {
  unsigned int x;
  unsigned int y;
} myStruct;

int main(void)
{
  FILE *myFile;
  myStruct xy;
  if ((myFile = fopen("filename.txt", "rb")) == NULL)
    return (1);
  if(fscanf(myFile, "%u %u", &xy.x, &xy.y) != 2)
    {
      fprintf(stderr, "Error!");
      return (1);
    }
  fclose(myFile);
  printf("x: %u, y: %u\n", xy.x, xy.y);
  return 0;
}

Upvotes: 4

Related Questions