1

我正在用 C 编写扫雷游戏。我希望能够玩具有不同大小和数量的地雷的不同雷区的游戏我创建了这样的结构来描述我的数据:

typedef struct t_Place Place;

struct t_Place{
    unsigned numberOfMinesNear;
    int mine;
    int state;
};

typedef struct t_Minefield Minefield;

struct t_Minefield{
    int xSize;
    int ySize;
    unsigned minesNumber;
    Place **places; 
};

所以,现在我正在尝试初始化我的雷区。我执行以下操作:

void makeGame(Minefield *minefield, unsigned x, unsigned y, unsigned mines){
    int i, j;  
minefield->places = malloc(x * y * sizeof(Place));       
    for(i = 0; i < x; i++)
        for(j = 0; j < y; j++){
            minefield->places[i][j].mine = EMPTY;
            minefield->places[i][j].state = HIDDEN;
            minefield->places[i][j].numberOfMinesNear = 0;
        }

minefield->xSize = x;
    minefield->ySize = y;

    unsigned minesToPlace = mines;
    srand(time(NULL));
    while(minesToPlace > 0){
        i = rand() % x;
        j = rand() % y;

        if(minefield->places[i][j].mine)
            continue;

        minefield->places[i][j].mine = MINE;
        minesToPlace--;      
    }  
    minefield->minesNumber = mines;
    // here will be call of play(minefield) function to start the game
}

int main(){
    Minefield *gameField = (Minefield *) malloc(sizeof(Minefield));

    makeGame(gameField, DEFAULT_X, DEFAULT_Y, DEFAULT_MINES);

    // DEFAULT_X = DEFAULT_Y = DEFAULT_MINES =  10

    free(gameField);
    return 0;
}

我在 makeGame 函数的第一行代码中遇到了段错误。我做错了什么?我想动态地而不是静态地为我的雷区分配内存。

4

2 回答 2

2
minefield->places = malloc(x * y * sizeof(Place)); 

上面的内存分配可能是问题的根源,places是一个两星指针,所以必须有两个malloc()调用,一个分配行号**place指针,另一个malloc()分配列号*place类型的指针place

这是分配/初始化包含在结构中的两星指针的SSCCE 。

#include <stdio.h>
#include <stdlib.h>

#define ROW_SZ 5
#define COL_SZ 25

typedef struct demo{
char **str;
}demo;


int main()
{

demo *d = malloc( sizeof(demo) );

d->str = malloc(ROW_SZ * sizeof(char*) );             //d->str is assigned char**
  for ( i = 0; i < ROW_SZ; i++ )
        d->str[i] = malloc(COL_SZ * sizeof(char) );   //d-str[i] is assigned char*

// code here to use d->str[ROW_SZ][COL_SZ]

for ( i = 0; i < ROW_SZ; i++ )
  free(d->str[i]);


free(d->str);
free(d);

return 0;
}
于 2013-03-15T18:10:40.913 回答
1

这就是我通常看到分配的二维数组的方式:

minefield->places = malloc(x * sizeof(Place *));       

for(i = 0; i < x; i++)
{
    minefield->places[i] = malloc(x * sizeof(Place));
}

试试这个,看看它是否会让你的段错误消失。

于 2013-03-15T18:16:10.883 回答