c - Fscanf into a structure -


i'm trying fscanf data struct, compiler ok code when try print it, doesn't print text. 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 need allocate space this? if have to, please show me how go doing that?

your not have structure there. pointer on structure. can either allocate memory malloc() or declare structure localy :

mystruct xy; 

there no need use malloc in 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; } 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -