Drakalex
Drakalex

Reputation: 1538

Can't store a struct containing a pointer

I have three structs :

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;

I use the map structure as a 2d dynamic array. Here are my functions to manipulate the 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;
}

Now what I'm doing is I'm creating a variable player of type Player, asks the user the width and height of the map and allocate memory for the map (malloc(sizeof(int)*width*height)). Next what I want to do is to be able to store the struct Player in a file and the values of the cases but I don't know how I could do it. Any suggestion ?

Upvotes: 0

Views: 400

Answers (1)

dbush
dbush

Reputation: 224167

You're not reading the values back in properly:

    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

In the first read, you pass in &player->games as the address to write to. This expression has type int **. Rather than writing into the memory you allocated, you're writing into the pointer that contains that address. The same problem exists in the other read.

Remove the address-of operator from each of the fread calls. Also, the calls to fseek are redundant since the file pointer is already at the correct place, so you can remove them.

    fread(player->games, sizeof(int), 1, file); // read the value
    fread(player->map.cases, sizeof(int), 1, file); // read the value

Upvotes: 2

Related Questions