0

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!

anastaciu
  • 23,467
  • 7
  • 28
  • 53
V_S
  • 27
  • 6
  • 1
    *"Now, I know you can't do this. "* - How do you know that? Because that's wrong. – klutt May 01 '21 at 18:33
  • Add extra `typedef`s in your c code to increase readability. See [this C reference](https://en.cppreference.com/w/c) and compile your C code with [GCC](http://gcc.gnu.org/) invoked with all warnings and debug info: `gcc -Wall -Wextra -g` and [this answer](https://stackoverflow.com/a/19526457/841108) – Basile Starynkevitch May 01 '21 at 18:36

2 Answers2

4

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
0
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 );
John Bode
  • 119,563
  • 19
  • 122
  • 198