I have this struct:
typedef struct {
char name[31];
int played;
int won;
int lost;
int tie;
int points;
} Player;
And this function which fill the struct array with data from file:
int load(Player *players[], int max_players, int *player_count)
{
static const char filename[] = "players.txt";
FILE *file = fopen(filename, "r");
if (file != NULL)
{
char line[128];
players = malloc(max_players * sizeof *players);
while (1) /* read until end of file */
{
players[*player_count] = malloc(sizeof(Player));
if (*player_count < max_players && fgets(players[*player_count]->name, sizeof players[*player_count]->name, file) != NULL)
{
fscanf(file, "%d", &players[*player_count]->played); // read played
fscanf(file, "%d", &players[*player_count]->won); // read won
fscanf(file, "%d", &players[*player_count]->lost); // read lost
fscanf(file, "%d", &players[*player_count]->tie); // read tie
fscanf(file, "%d", &players[*player_count]->points); // read points
fgets(line, sizeof line, file); // read new line
// increase player count
*player_count += 1;
}
else
{
break;
}
}
fclose(file);
}
else
{
return 0;
}
return 1;
}
Now I am having a problem with calling it by passing players as a reference so that the updated data of players gets reflected at the calling end.
Below is my calling code, which I think has the problem:
Player *players[MAX_PLAYERS] = { NULL };
int playerCount = 0;
load(players, MAX_PLAYERS, &playerCount);
When I debug the code, the players' array gets filled in the function but when it returns back, the players' value is still null.
Any help would be appreciated.