无法存储包含指针的结构

标签 c pointers dynamic struct save

我有三个结构:

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/

相关文章:

c++ - 如何检测应用程序是否在 KVM 下运行?

c++ - 从另一个非进程和日志堆栈发送信号到线程没有发生

python - 在 <= 1 MB RAM 和 <= 10 MB ROM 的设备上运行支持 vector 机内核是否可行?

c - C中的算术运算给出奇怪的值

c - 如何将 .txt 文件的内容打印为字符串?

c++ - 绘制 Sprite 导致 Segmentation Fault

C++:二维数组中的指针令人困惑

css - 为宽度和高度创建灵活的布局

c# - 使用 Entity Framework 的 sql IN 子句的动态 linq 查询表达式树

C#:如何动态加载/实例化 DLL?