Nick
Nick

Reputation: 6940

Struct Field undeclared in main

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( "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!

Upvotes: 0

Views: 737

Answers (1)

user470379
user470379

Reputation: 4887

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.

Upvotes: 5

Related Questions