You can absolutely use int (*p)[Cols]
, it's a pointer to array of size Cols
(Cols
times size of int
, in bytes), you just have to allocate memory for it, until you do, it doesn't point to a valid memory location. The constraint is that the allocated memory needs to be in blocks of multiples of Cols
:
int (*p)[Cols] = malloc(sizeof *p); //prefered
Or
int (*p)[Cols] = malloc(sizeof(int) * Cols); //alternative
In both of the above expressions, supposing Cols
's value is 10, p
will point to a block of memory that can take 10 int
s.
Usage:
for (int i = 0; i < Cols; i++)
{
p[0][i] = i;
}
The above expresssions only allocated space for one line of int
s, but since p
is a pointer to array, you can allocate space for as many of them as you want (given the memory constraints).
Let's assume you want an array with 5 lines and Cols
columns:
int (*p)[Cols] = malloc(sizeof *p * 5);
Usage:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < Cols; j++)
{
p[i][j] = i * j;
}
}
As you (probably) know this kind of construct is primarily used to emulate a 2D array, one of the advantages is that you can then free all the memory with a single free:
free(p);
Whereas constructs like an array of pointers, or a pointer to pointer would force you have multiple free
s.