首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用malloc创建由枚举组成的动态2D数组时分割保险库

使用malloc创建由枚举组成的动态2D数组时分割保险库
EN

Stack Overflow用户
提问于 2015-01-04 17:32:07
回答 1查看 67关注 0票数 0

首先,我不是英语本地人,所以写这样的东西对我来说很困难,而且我是新来的。嗨:)

我在虚拟机上使用Linux和gcc。我用的是诅咒。我已经设法改正这个错误好几个小时了;

1.)这是我的心愿:

代码语言:javascript
复制
// Codes on the board
enum BoardCodes {
    BC_FREE_CELL = 1,    // Cell is free
    BC_USED_BY_WORM = 2, // Cell occupied by worm
    BC_FOOD_1 = 3,       // Food type 1; if hit by worm -> bonus of type 1
    BC_FOOD_2 = 4,       // Food type 2; if hit by worm -> bonus of type 2
    BC_FOOD_3 = 5,       // Food type 3; if hit by worm -> bonus of type 3
    BC_BARRIER = 6,       // A barrier; if hit by worm -> game over
};

2.)这是单元格变量,在我的结构“蠕虫”中:

代码语言:javascript
复制
enum BoardCodes **cells;

3.)这就是我要创建数组的方式:

代码语言:javascript
复制
aboard->cells = malloc((aboard->last_row +2)*sizeof(int*));
if(aboard->cells == NULL) {
    showDialog("Abbruch: Zu wenig Speicher","Bitte eine Taste drücken");
    exit(RES_FAILED); // No memory -> direct exit
}   
int y;
for (y = 0; y < aboard->last_row; y++) {
    // Allocate array of columns for each y
    aboard -> cells[y] = malloc((aboard->last_col + 2)*sizeof(int));
    if((aboard -> cells[y]) == NULL) {
        showDialog("Abbruch: Zu wenig Speicher. Code2","Bitte eine Taste drücken");
    }   
}   

在showDialog里面写着“内存不足,按任意键”

4.)我用gdb调试了它。分割错误发生在这里:

代码语言:javascript
复制
aboard->cells[y][x]=board_code;

(gdb) print x
$3 = 40
(gdb) print y
$4 = 10
(gdb) print aboard->last_col
$5 = 165
(gdb) print aboard->last_row
$6 = 28
(gdb) print board_code
$7 = BC_BARRIER

5.)我试图打印数组的值:

代码语言:javascript
复制
(gdb) print aboard->cells[1][1]
$9 = 3087007176
(gdb) print aboard->cells[1][2]
$10 = 3251580

但它们应该是BC_FREE_CELL:

代码语言:javascript
复制
void fillwithfreebcs(struct board* aboard)
{
    int y=0;
    int x=0;
    //fill board and screen buffer with empty cels
    for (y = 0; y < aboard->last_row; y ++) 
    {   
        for(x = 0; x < aboard->last_col ; x++ ) { 
              aboard->cells[y][x] = BC_FREE_CELL;
              //placeItem(aboard,y,x,BC_FREE_CELL,SYMBOL_FREE_CELL,COLP_FREE_CELL);
        }   
    }
}

(非常感谢:)

(当我使用enum *而不是int*时,出现了相同的错误消息。)

rgds,Tobi

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-07 10:02:55

我太抱歉了

使用malloc的代码从未被执行,因为我忘记删除.

哈哈

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27768314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档