Angus Comber
Angus Comber

Reputation: 9708

How to create at runtime a two dimensional array in C

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?

Upvotes: 3

Views: 12632

Answers (5)

Staven
Staven

Reputation: 3165

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);

Upvotes: 11

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

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.

Upvotes: 7

Jonathan Leffler
Jonathan Leffler

Reputation: 753575

Some of the examples show multiple (more than 2) allocations for the array; it is perfectly feasible to do it in just two allocations (error checking omitted) for an n × m array:

int **array = calloc(m, sizeof(*array));
int *data   = calloc(m * n, sizof(*data));

for (int i = 0; i < m; i++)
    array[i] = &data[i * n];


...use array[i][j]...

free(array[0]);
free(array);

Upvotes: 0

Jens
Jens

Reputation: 72639

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?

Upvotes: 1

Dan Bizdadea
Dan Bizdadea

Reputation: 1302

In C a multidimensional array is just an array for which each element is another array.

So you need to first allocate memory for one array (the rows). You can use the malloc() function which will return a pointer to the array.

Then you iterate through the array and for each element you allocate memory for the number of columns.

NOTE: don't forget to free the memory you manually allocate with the free() function in the same way you used malloc() to allocate it.

Upvotes: 0

Related Questions