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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With