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!
You can absolutely use
int (*p)[Cols]
, it's a pointer to array of sizeCols
(Cols
times size ofint
, 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 ofCols
:Or
In both of the above expressions, supposing
Cols
's value is 10,p
will point to a block of memory that can take 10int
s.Usage:
The above expresssions only allocated space for one line of
int
s, but sincep
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:Usage:
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:
Whereas constructs like an array of pointers, or a pointer to pointer would force you have multiple
free
s.