我有这个结构和功能:
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
函数一次性执行 malloc
和 strcpy
。
奖杯
和移动
也会出现同样的问题;最后你应该每次检查token1 != NULL
。
关于c - 我无法为此结构分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281929/