如何将双指针用于二维矩阵? [英] How can a double pointer be used for a two dimensional matrix?

查看:190
本文介绍了如何将双指针用于二维矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过实施Conway的《人生游戏》来尝试C.

I am trying my hand at C by implementing Conway's game of Life.

我试图动态地构建两个网格(int矩阵),一个用于当前网格,一个用于下一代网格,因此在确定下一代的外观之后,我只是交换指针.

I am trying to dynamically build two grids (int matrices), one for the current and one for the next generation, so after I determine what the next generation looks like, I just swap pointers.

起初,我无可救药地尝试定义指向int * grid之类的网格的指针,您不能使用像[][]这样的第二组括号来下标,因为-很显然,第一组括号返回一个int.

At first I tried hopelessly to define the pointer to the grid like int * grid, which you cannot subscript with a second set of brackets like [][] because - obviously - the first set of brackets returns an int.

我也尝试了类似int * grid[HEIGHT][WIDTH]的方法,但这给将这样一个指针分配给另一个指针带来了问题. (实际上,我不知道它在内存中到底有什么作用!)

I also tried something like int * grid[HEIGHT][WIDTH], but this gives problems assigning one pointer like this to another. (And in fact, I have no idea what this really does in memory!)

出于天真的希望,我认为以下内容在跨过双指针后可能会起作用.该程序可以编译,但是在指定的行上运行时会失败. (在Windows中,除了问题事件名称"为APPCRASH之外,我没有其他详细信息.)

In my naïve hopefulness, I thought the following could work after stumbling across double pointers. The program compiles, but fails when running on the line indicated. (In Windows, I get no more detail other than that the Problem Event Name is APPCRASH).

免责声明:这不是实际程序,仅是问题的概念证明.

DISCLAIMER: This is not the actual program, just a proof of concept for the problem.

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

int HEIGHT = 20;
int WIDTH = 20;

int ** curr_gen; // Current generation
int ** next_gen; // Next generation

/* Entry Point main */
int main(int argc, char** argv) {

    // Allocate memory for the grids
    curr_gen = malloc(sizeof (int) * WIDTH * HEIGHT);
    next_gen = malloc(sizeof (int) * WIDTH * HEIGHT);

    curr_gen[0][0] = 0; //<< PROGRAM FAILS HERE

    // Release heap resources
    free(curr_gen);
    free(next_gen);

    return 0;
}

推荐答案

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆