开发者

Struct Field undeclared in main

开发者 https://www.devze.com 2023-02-14 04:39 出处:网络
Hey all, I\'m writing a C program, and I want to have an array of structs malloc\'d up and filled with data from a file. Here\'s my typedef for the struct:

Hey all, I'm writing a C program, and I want to have an array of structs malloc'd up and filled with data from a file. Here's my typedef for the struct:

typedef struct {
   char name[5];
   int age;
} person;

And then in my main function I do this:

  person *A ;
  int  i ;
  FILE * fin;

  fin = fopen( "people", "r" );

  A = ( person * ) malloc( sizeof(person) * 10 );
  if ( A == NULL ) { printf开发者_如何学Python( "Error mallocing \n" ) ; return -1 ; }

  for( i = 0; i < 10; i++ ) {

    fscanf( fin, "%s %d", name->A[i], age->A[i] );

  }

Now unfortunately when I try to compile I get the error that name and age are undeclared in main. I've never tried using fscanf to make structs before, but I'm at a bit of a loss here. Thanks in advance to anyone who knows anything!


You just accidentally got your syntax backwards (that and the fact that indexing the pointer returns an actual struct, not a pointer to it so the pointer to member operator -> is not needed): A[i].name and &(A[i].age). Also checking the return value from fopen might be a good idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消