Very new to C and I am trying to figure out (for an assignment) how to properly use structs and functions. Specifically, I am having trouble working out how to pass an array of structs from a function.
The function is supposed to take data from a file and input into an array. The input file has the following data: 1 Al 2 Bill 3 Clark 4 Dean 5 Ellen
After I call the function, I would like to be able to view the array values in the main function.
I don't think I'm passing the struct correctly but am not sure where I'm going wrong. Any suggestions? Thanks.
Here is my code attempt:
// Input file into array
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int number;
char name[30];
} Name;
#define SIZE 5
// function prototypes
int loadName( char *file, Name N[] );
// function main begins program execution
int main( void )
{
char file[ 30 ]; // file name
Name N[ SIZE ]; // array to store names
size_t i, j=0; // counter
// check read function opens file correctly
if (-1 == ( i = loadName ( file, N ) ) ) {
puts( "Employee file could not be opened" );
} // end load if
printf("\n\nCheck for names in main function\n\n");
for (j=0; j<i; ++j) {
printf("%8d%18s\n", N[j].number, N[j].name );
}
return 0;
free(N);
}
// load values from name file
int loadName( char *file, Name N[] )
{
FILE *inPtr; // inPtr = input file pointer
size_t i = 0; // counter
// fopen opens file. Exit program and return -1 if unable to open file
if ( ( inPtr = fopen( "name.txt", "r" ) ) == NULL ) {
return -1;
} // end if
else {
printf("Employee Number Employee Name\n" );
// read name from file
do {
N = (Name*)malloc(100);
fscanf( inPtr, "%d%s", &N[i].number, &N[i].name );
printf("%8d%18s\n", N[i].number, N[i].name );
i++;
} while (!feof( inPtr ));
} // end else
fclose( inPtr ); // fclose closes the file
return i; // return i after successful for loop
} // end function loadname