Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamic allocate a two dimensional array

I would like to make a two dimensional array in C.

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.

Edit:

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.

like image 624
Zwiebel Avatar asked Dec 27 '22 13:12

Zwiebel


1 Answers

Let place be a pointer to arrays,

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;
like image 187
Daniel Fischer Avatar answered Jan 10 '23 00:01

Daniel Fischer