Reputation: 1615
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.
Upvotes: 4
Views: 7827
Reputation: 1352
You need to do the following to allocate arr[x][y] of type int dynamically:
int i = 0;
int **arr = (int**)calloc(x, sizeof(int*));
for(i = 0; i < x; i++)
arr[i] = (int *) calloc(y, sizeof(int));
The idea is to first create a one dimensional array of pointers, and then, for each array entry, create another one dimensional array.
Upvotes: 0
Reputation: 4114
You could use a single 1d array as a 2d array by some smart indexing :
Allocate memory :
place = (int*) malloc(rows * columns * sizeof(int));
To access place[i][j]
, use i and j as :
place[ i*columns + j] = value ;
Upvotes: 0
Reputation: 183978
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;
Upvotes: 10