c - 结构体中的二维数组

标签 c

我必须实现生命游戏,它几乎完成了,我想做的最后一件事就是分配我的场动态。我在 Windows 下工作,没有 Valgrind,我不知道我的代码中有什么错误。 Eclipse 仅显示该进程不再起作用。

谁能告诉我,我的代码有什么问题吗?或者也许我不需要 2 暗淡。生命游戏场数组?

struct game_field  {
    int length;
    int **field;
};


static struct game_field *new_game_field(unsigned int l) {
    struct game_field *pstField;
    pstField = calloc(1, sizeof(struct game_field));
    pstField->length = l;
    pstField->field = malloc(l * sizeof(int*));
    for( int i = 0; i < l; i++ ) {
        pstField->field[i] = malloc(l * sizeof(int));
        if(NULL == pstField->field[i]) {
             printf("No memory for line %d\n",i);
        }
    }
    return pstField;
}

最佳答案

您应该稍微考虑一下结构和存储的内容。

对于生命游戏,您需要知道棋盘上单元格的状态,该状态由整数表示,因此您的结构应变为:

struct game_field  {
   int length;
   int *field;
};

一旦你知道了字段的尺寸,你就应该分配它一次:

struct game_field *gf = calloc(1, sizeof(struct game_field));
gf->length = <blah>;
gf->field = malloc(gf->length*gf->length*sizeof(int));

这样你就有了一个可以用作棋盘的整数数组。

关于c - 结构体中的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8760288/

相关文章:

c - 删除 C 中的多字符常量

c - 反向存储值(value)?

c - 为什么 iconv 命令输出到同一个文件被截断?

c++ - 在 C 中包装 C++ 成员函数 - Visual Studio 2013 模板问题

c - 无法理解在 inet_ntoa 函数中完成的类型转换

c - 在 switch case 语句中实现时如何使函数正确运行

c - 为什么函数必须返回 char * 而不是 char 数组?

对结构的 C 代码引用

c - 尝试释放时出现堆错误

c - 指针周围存在大量内存泄漏