gpt4 book ai didi

c - strtok 分配给数组结构失败

转载 作者:行者123 更新时间:2023-11-30 19:42:12 25 4
gpt4 key购买 nike

我有这个函数,但不起作用,在 ubuntu 中,当我调用该函数时,向我显示段错误(核心转储):

void loadSavedGame(char fileName[], struct saveGame *savedGamesReaded[], int *length, int *statusCode){

char line[500];
char *token2;
int x=0;

*savedGamesReaded = (struct saveGame*)malloc((*length)*sizeof(struct saveGame)); //reserve memory for pointer and array elements

int j;
for(j=0; j<*length; j++){
(*savedGamesReaded)[j].id = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].score = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].position = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].maze_level = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].achievements = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].time_playing = (char *)malloc(MAX_STRING*sizeof(char));
(*savedGamesReaded)[j].virtual_players = (char *)malloc(MAX_STRING*sizeof(char));
}


while (feof(file) == 0){ //file its a text plane was opened before
fgets(line,500,file);
token2 = strtok(line,":"); // Here the program falls on the fourth loop
strcpy((*savedGamesReaded)[x].id, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].score, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].position, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].maze_level, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].achievements, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].time_playing, token2);
token2 = strtok(NULL,":");
strcpy((*savedGamesReaded)[x].virtual_players, token2);
x++;
}
fclose(archivo);


}

我这样声明结构:

struct saveGame{
char *id;
char *score;
char *position;
char *maze_level;
char *achievements;
char *time_playing;
char *virtual_players;
};

我认为 strtok 不起作用,但我不知道为什么,也许 token 中的 NULL 是错误的?

strcpy((*savedGamesReaded)[x].id, token2);
token2 = strtok(NULL,":");

最佳答案

这行代码的作用与您想象的不同:

while (feof(file) == 0){ //file its a text plane was opened before

feof() 仅在达到 EOF 后返回 true。请参阅Why is “while ( !feof (file) )” always wrong?

并且您从不检查此行是否成功:

fgets(line,500,file);

此外,您不关闭文件:

fclose(archivo);

关于c - strtok 分配给数组结构失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32595111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com