我有这个结构:
typedef struct {
char name[31];
int played;
int won;
int lost;
int tie;
int points;
} Player;
这个函数用文件中的数据填充结构数组:
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;
}
现在我在通过传递玩家作为引用来调用它时遇到问题,这样玩家的更新数据就会反射(reflect)在调用端。
下面是我的调用代码,我认为有问题:
Player *players[MAX_PLAYERS] = { NULL };
int playerCount = 0;
load(players, MAX_PLAYERS, &playerCount);
当我调试代码时,函数中填充了玩家的数组,但当它返回时,玩家的值仍然为空。
如有任何帮助,我们将不胜感激。
最佳答案
您正在覆盖局部变量 players
。
从您不需要的函数中删除以下行。
players = malloc(max_players * sizeof *players);|
因为您已经在 main
中有了指针数组。
你不需要Player
类型的指针数组你只需要Player
类型的数组
Player *players;
load(&players, MAX_PLAYERS, &playerCount);
并且在load
函数中。
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 */
{
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;
}
关于C - 如何通过引用将结构指针数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615662/