我有三个结构:
struct Map
{
int width, height;
int* cases;
};
typedef struct Map Map;
struct Ship
{
int x, y, length, firstShoot, color, hasBeenDiscovered;
};
typedef struct Ship Ship;
struct Player
{
int activeShips;
Map map[2];
char lastMoves[5][128];
Ship ships[10];
int shipcolor[4];
int color;
};
typedef struct Player Player;
我将 map 结构用作二维动态数组。这是我操作 map 的函数:
void mallocMap(Map* map, int width, int height)
{
map->cases = malloc(sizeof(int) * width * height);
map->width = width;
map->height = height;
if (map->cases == NULL)
{
printf("Erreur d'allocation de memoire\n");
exit(0);
}
}
void freeMap(Map* map)
{
free(map->cases);
}
int getMapValue(Map map, int x, int y)
{
return *(map.cases + y*map.width + x);
}
void setMapValue(Map* map, int value, int x, int y)
{
*(map->cases + y*map->width + x) = value;
}
现在我正在做的是创建一个 Player 类型的变量播放器,询问用户 map 的宽度和高度并为 map 分配内存 (malloc(sizeof(int)*width*高度)
)。
接下来我想做的是能够将 struct Player 和 case 的值存储在一个文件中,但我不知道该怎么做。
有什么建议吗?
最佳答案
您没有正确读回这些值:
fseek(file, sizeof(Player), SEEK_SET); // set the cursor after the struct
fread(&player->games, sizeof(int), 1, file); // read the value
fseek(file, sizeof(int), SEEK_CUR); // set the cursor after the first value
fread(&player->map.cases, sizeof(int), 1, file); // read the value
在第一次读取时,您传入 &player->games
作为要写入的地址。此表达式的类型为 int **
。您不是写入您分配的内存,而是写入包含该地址的指针。另一个read也存在同样的问题。
从每个 fread
调用中删除 address-of 运算符。此外,对 fseek
的调用是多余的,因为文件指针已经位于正确的位置,因此您可以将其删除。
fread(player->games, sizeof(int), 1, file); // read the value
fread(player->map.cases, sizeof(int), 1, file); // read the value
关于无法存储包含指针的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47332521/