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

标签 c arrays struct strtok

我有这个函数,但不起作用,在 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/

相关文章:

c++ - 由 C++ 编译器优化时,F2C 翻译的代码会中断

php - 删除嵌套foreach PHP中的嵌套数组

arrays - 使用 awk 根据两个字段删除文件中的冗余

arrays - 了解 word2vec (TensorFlow) 中的输入和标签

generics - 如何将通用特征设置为函数参数的类型?

c - 在函数之间传递结构

c - 需要有关文件指针处的段错误的帮助

c - 将结构别名设置为空

C++ 处理 'struct' 和字符串

c - 将字节转换为位数组? C