I am trying to pass an array of structures to a function, and then have that function process a file and fill the array of structures with values. The file is a text file containing:
Gates M 60
Jobs M 55
Jane F 45
which would fill the structure of arrays. ex. person[0] should contain Gates M 60. Currently I do not get any errors for this program but it simply does not process the file into the structure at the fscanf. Am I referencing the structure wrong?
I was also wondering if there was a way to make the for loop work for any size of array of structures-- meaning what could I replace the "2" condition in my for loop with in order for it to just continually fill an array of adequate size until it ran out of information to process?
#include <stdio.h>
struct Person
{
char lastname[30];
char gender;
unsigned int age;
};
int function(struct Person array[])
{
FILE *cfPtr;
if((cfPtr = fopen("C:\\Users\\Nick\\Desktop\\textfile","r"))==NULL)
{
printf("File cannot be opened");
}
else
{
for(int i=0;i<2;i++)
{
fscanf(cfPtr,"%10s %c %3d",&array[i].lastname,&array[i].gender,&array[i].age);
}
}
}
int main(void)
{
struct Person person[3];
function(&person[3]);
printf("%s %c %d\n",person[0].lastname, person[0].gender, person[0].age);
printf("%s %c %d\n",person[1].lastname, person[1].gender, person[1].age);
printf("%s %c %d\n",person[2].lastname, person[2].gender, person[2].age);
}
reallocis for and is how resizable vectors work in other languages (e.g.ArrayListin Java,List<T>in .NET,vector<T>in C++ STL). Use a heap-allocated array (struct Person* people = calloc( sizeof(struct Person), 10 )instead of an automatic array.char*instead of fixed-length character buffers and then dynamically allocate usingcallocormallocorstrdup. Also use loops and don't just spam-paste a bunch of largely identical lines.&person[0]. An array defined asx[3]has entries numbered with indexes0..2.