If you are just allocating a 4-element array of int
, you'd write
int (*p)[4] = malloc( sizeof *p );
or
int (*p)[4];
...
p = malloc( sizeof *p );
Since the type of p
is "pointer to 4-element array of int
", the type of the expression *p
is "4-element array of int
", so sizeof *p
gives us the right number of bytes to allocate (sizeof (int [4])
).
You'd access each element as
(*p)[i] = x;
The parentheses are necessary. Remember that the type of the expression *p
is "4-element array of int
", so we want to apply the []
operator to the result of that expression. Since []
has higher precedence than unary *
, we need to explicitly group the *
operator to p
with the parentheses.
You could also write p[0][i] = x
, since p[0]
is synonymous with *p
. This gets rid of the explicit dereference, but it treats p
as a 2D array, which may be confusing.
Because of that confusion, this isn't the usual way of allocating a 1D array; the usual practice is to write
int *p = malloc( n * sizeof *p );
...
p[i] = x;
Since the type of p
is "pointer to int
", the type of the expression *p
is simply int
, so we need to specify the number of int
s we want in the malloc
call. Since p
is a simple pointer to int
, we can apply the subscript operator to it directly without having to dereference it first.
If you're allocating an Nx4-element array of int
, you'd write
int (*p)[4] = malloc ( N * sizeof *p );
and you'd access each element as
p[i][j] = x;
Since the type of the expression p
is "pointer to 4-element array of int
", the type of the expression p[i]
is "4-element array of int
", thus we don't need to explicitly dereference p
.
So, to sum up:
- Allocating and using a single element of type
T
: T *p = malloc( sizeof *p );
*p = ...;
free( p );
- Allocating and using a 1D array of
T
: T *p = malloc( N * sizeof *p );
p[i] = ...;
free( p );
- Allocating and using a 2D array of
T
: T (*p)[N] = malloc ( M * sizeof *p );
p[i][j] = ...;
free( p );
- Allocating and using a 3D array of
T
: T (*p)[M][N] = malloc (K * sizeof *p );
p[i][j][k] = ...;
free( p );
The pattern for higher-dimension arrays should be clear.