How to create at runtime a two dimensional array in C
Solution 1
You have to allocate a 1-dimensional array:
int* array = calloc(m*n, sizof(int));
And access it like this:
array[i*n + j]
The compiler does exactly this when accessing two-dimensional arrays, and will probably output the same code when n
can be guessed at compile time.
Solution 2
First allocate an array of pointers.
/* size_x is the width of the array */
int **array = (int**)calloc(size_x, sizeof(int*));
Then allocate each column.
for(int i = 0; i < size_x; i++)
{
/* size_y is the height */
array[i] = (int*)calloc(size_y, sizeof(int));
}
You can access the elements with array[i][j]
. Freeing the memory is done in 'reverse' order:
for(int i = 0; i < size_x; i++)
{
free(array[i]);
}
free(array);
Solution 3
This is a FAQ on comp.lang.c (I took the liberty to add the c-faq tag), it even has a FGA (frequently given answer :-) See http://c-faq.com/aryptr/index.html, 6.16 How can I dynamically allocate a multidimensional array?
Angus Comber
Updated on June 08, 2022Comments
-
Angus Comber almost 2 years
I cannot create a 2D array from 2 variables (eg
int arr[i][j]
not allowed) so how would I create a dynamically sized 2D array?The dimensions of the array are only known at runtime in my program. The array is to represent a grid. How would I code this in C?