如何动态分配的二维阵列 [英] How to dynamic allocate a two dimensional array
问题描述
我想提出在C二维数组。
I would like to make a two dimensional array in C.
例如,我做指定的地点这样的一个int型变量:
For example, I make an int type variable named place like this:
int *place;
我有一个游戏,它有像行和列变量。
我想我的地方变量是一个二维数组,它的行和列(数组的最大大小),它看起来像这样的正常的声明动态分配:
I have a game, which have variables like rows, and columns. I would like my place variable to be a two dimensional array, with dynamic allocation of its rows and columns (for the max size of the array), which would look like this in the "normal" declaration:
place[rows][columns];
但我不知道如何与动态分配去做。
but I don't know how to do it with the dynamic allocation.
我会做这样的一维数组:
I would do it like this for one-dimensional arrays:
place = (int*) malloc (levels * sizeof(int));
但我不知道如何使用二维数组做到这一点。
but I don't know how to do this with 2D arrays.
编辑:
我怎么能对字符,而不是INT改写呢?
How I can rewrite this for char instead of int?
我试图只是简单地覆盖与字符的整数,但它不能正常工作。
I have tried to just overwrite the ints with chars, but it doesn't work.
推荐答案
让地方
是一个指针数组,
int (*place)[columns] = malloc(rows * sizeof *place);
这是给你的内存(好地方)一个连续的块,你可以简单地用
That gives you a contiguous block of memory (good for locality) that you can simply access with
place[i][j] = whatever;
这篇关于如何动态分配的二维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!