vj1207 vj1207 - 1 month ago 13
C++ Question

Allocating memory for array of pointers of int dynamically

If I want to dynamically allocate memory for array of pointers of int, how can I achieve this requirement?

Suppose I declare an array of pointers of int like this:

int (* mat)[];


Is there a way I can allocate memory for K number of pointers dynamically and assign it to mat? If I do

mat = new int * [K];


It gives error :
cannot convert 'int**' to 'int (*)[]' in assignment
. I understand this memory allocation is implicitly got converted to int **. Is there any way to allocate memory for above scenario?

Even when I try to assignment of statically allocated array of pointers of int to array of pointers of int, like this:

int (*mat)[] = NULL;
int (* array_pointers)[26];
mat = array_pointers;


Compilation gives this error:
cannot convert 'int (*)[26]' to 'int (*)[]' in assignment
.

Can someone please explain to me why this is an error or why it should be an error?

M.M M.M
Answer

In C, int (* mat)[]; is a pointer to array of int with unspecified size (not an array of pointers). In C++ it is an error, the dimension cannot be omitted in C++.

Your question says new int *[K] so I assume this is really a C++ question. The expression new T[n] evaluates to a T * already, there is no implicit conversion.

The code to allocate an array of null pointers using new is:

int **mat = new int *[10]();

Then mat points to the first one of those. Another option (less commonly used) is:

int * (*mat)[10] = new int *[1][10]();

where *mat designates the entire array of 10 pointers.

NB. This sort of code is not useful for anything except demonstration purposes perhaps, whatever you are trying to do has a better solution.