As of C99, you can define an array's size at runtime using variable length arrays:
int x = some_value();
int y = some_other_value();
int arr[x][y];
Since their size isn't determined until runtime, there are some restrictions on their use - they can't have static
storage duration (i.e., they can't declared at file scope or with the static
keyword), and you can't use an initializer in the declaration. You also want to be careful if x
or y
are large.
If you don't have a C99 or later compiler available, then this won't work. You'll have to use dynamic memory allocation instead, and you'll have to allocate it as a "jagged" array:
int x = some_value();
int y = some_other_value();
int **arr = malloc( sizeof *arr * x );
if ( arr )
{
for ( size_t i = 0; i < x; i++ )
{
arr[i] = malloc( sizeof *arr[i] * y );
}
}
When you're done, you'd deallocate as
for (size_t i = 0; i < x; i++ )
free( arr[i] );
free( arr );
This will work like any other 2D array when it comes to accessing elements:
arr[i][j] = some_value();
but be aware that the rows will not be contiguous - there will be gaps from the end of one row to the beginning of the next row. If that matters, then the last option is to declare a 1D array and manually compute the index:
int *arr = malloc( sizeof *arr * x * y );
...
arr[i * x + j] some_value();
When you're done, you'd free it as
free( arr );