Regardless of the type, allocating a N
xN
array takes one of the following forms:
If N
is known at compile time, or if variable-length arrays are supported, it's easy:
T (*arr)[N] = malloc( sizeof *arr * N );
Elements are accessed as arr[i][j]
. When you're done, you'd free them as
free( arr );
If N
is not known at compile time and VLAs are not supported and all array elements must be contiguous, then you'd need to allocate a 1D array and compute the offset:
T *arr = malloc( sizeof *arr * N * N );
...
x = arr[ i * N + j ];
If the array elements don't have to be contiguous, you can do a piecewise allocation:
T *arr = malloc( sizeof *arr * N );
if ( arr )
{
for ( size_t i = 0; i < N; i++ )
{
arr[i] = malloc( sizeof *arr[i] * N );
}
}
You'd access this array as arr[i][j]
, but since you allocated it piecewise, you must free it the same way:
for ( size_t i = 0; i < N; i++ )
free( arr[i] );
free( arr );
If you want to initialize your array elements to all-bits-0, use calloc
instead of malloc
:
T (*arr)[N] = calloc( N, sizeof *arr );
If you want to initialize your array elements to something other than all-bits-zero, then that depends on what T
looks like. If T
is, say, a structure type containing two integer elements, and you're using a C99 or later compiler, you could use a compound literal combined with memcpy
:
memcpy( arr[i], ( struct foo [] ){ {1,2}, {3,4}, {5,6}, {7,8} ... } );