c - 我无法为此结构分配内存

标签 c struct

我有这个结构和功能:

typedef struct{

       char *maze_size;
       char *trophy;
       int time_max;
       char *moves;

}gameHistory;

该函数接收指针gameHistory *gameHistoryReaded来保留内存,但不起作用。

void loadGameHistory(char fileName[], gameHistory *gameHistoryReaded, int *statusCode){
       /*  Here send error  */
       *gameHistoryReaded = (gameHistory*)malloc(LENGTH_GAME_HISTORY*sizeof(gameHistory));
       (*gameHistoryReaded).maze_size = (char *)malloc(MAX_STRING*sizeof(char));
       (*gameHistoryReaded).trophy = (char *)malloc(MAX_STRING*sizeof(char));
       (*gameHistoryReaded).moves = (char *)malloc(MAX_STRING*sizeof(char));

       FILE *file = fopen(fileName,"rb");
       char line[200];
       char *token1;
       if (file == NULL){
            printf("\nError de lectura: archivo no encontrado\n");
            *statusCode = 0; //Si se presenta algun error en la lectura del archivsetea en 0 (error)
            exit(1);
        }
        fgets(line,200,file);
        token1 = strtok(line,":");
        strcpy((*gameHistoryReaded).maze_size, token1);
        token1 = strtok(NULL,":");
        strcpy((*gameHistoryReaded).trophy, token1);
        token1 = strtok(NULL,":");
        strcpy((*gameHistoryReaded).moves, token1);
        token1 = strtok(NULL,":");
        (*gameHistoryReaded).time_max = atoi(token1);

        fclose(file);

}

int main(){

        char routegameHistory[] = "game_history.txt";
        int statusCode = 1;
        gameHistory gameHistory;

        loadGameHistory(routegameHistory, &gameHistory, &statusCode);

 }

Code::Blocks 向我展示了这个:

错误:从类型“struct gameHistory *”分配给类型“gameHistory”时出现不兼容的类型

但我认为struct声明得很好, 其他一点, 我为 int time_max 分配内存?

最佳答案

gameHistory gameHistory; 是一个错误。类型名不能重新用作变量名。假设您的意思是:

gameHistory history;

这已经分配了内存。您不需要分配任何额外的内存。只需从函数中删除尝试的 malloc 行,一切都会好起来的。

但是,在您的函数中进一步会出现问题:

strcpy((*gameHistoryReaded).maze_size, token1);

到目前为止,您还没有将 maze_size 指向任何地方,因此您无法将字符复制到其中。您可以将 maze_size 设为 char 数组(在这种情况下,不需要更多分配),或者您可以分配空间并指向该空间:

gameHistoryReaded->maze_size = strdup(token1);

strdup 函数一次性执行 mallocstrcpy

奖杯移动也会出现同样的问题;最后你应该每次检查token1 != NULL

关于c - 我无法为此结构分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281929/

相关文章:

c - 当我循环传递结构时,如何检查结构是否包含任何数据?

c - error C2071 非法存储类,在 C 中定义枚举类型

c - (C) 如何使用动态内存进行字符输入?如何以某种方式组织输入的值?

c - 链表添加函数导致段错误

Java 与 C 运行时(REPOST)

c - 具有结构体字段指针的结构体

c - 没有命名成员的结构在哪里有用?

c - C 结构语法中的括号

c - N个按概率随机选择

dlopened 模块可以调用调用者中的函数吗?