我的简单游戏中的内存分配

时间:2013-03-15 17:29:20

标签: c memory

我正在用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函数的第一行代码中遇到了段错误。我做错了什么?我想动态地为我的雷区分配内存,而不是静态。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

我通常会看到分配的2D数组:

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

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

试试这个,看看它是否会让你失误。