How can you dynamically allocate a pointer in the form int (*p)[n] in C?

550 Views Asked by At

Suppose I get input from somewhere and store it in a variable. Pretend the variable is Cols.

I want to make an array in the form

int (*p)[Cols]

Now, I know you can't do this. So how would I dynamically allocate it to do it?

Teaching me how to do so would really be appreciated!

2

There are 2 best solutions below

5
On

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 ints.

Usage:

for (int i = 0; i < Cols; i++)
{
    p[0][i] = i;
}

The above expresssions only allocated space for one line of ints, 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 frees.

0
On
int (*p)[Cols] = malloc( sizeof *p * Rows );

allocates enough space for a Rows x Cols array of int and assigns the address of that array to p. You can then access each element as p[i][j].

To deallocate all you need is

free( p );