InvisibleWolf
InvisibleWolf

Reputation: 1017

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?

Upvotes: 3

Views: 3408

Answers (2)

Ivan Rubinson
Ivan Rubinson

Reputation: 3329

In C and C++, in some cases, arrays and pointers are interchabgable. int*[] decays in to int**.

To dynamically allocate an array, use:

int* mat;
// ...
mat = new int[size];
// ...
delete[] mat;

Note that you need to delete all memory you take with new, or else you'll leak memory. It's not always easy to do.

C++ has a thing called RAII to help. To use RAII (meaning all resources taken in a scope will be released when the scope ends), put the new in a classes constructor, and delete in the destructor.

The STL has some comtainers ready for you to use. Look in to std::vector.


If you want an array of pointers as opposed to a dynamic array, the syntax is more like

int** arr = new int[size];
arr[i] = &val;
// ...
delete[] arr;

Don't forget to initialize each pointer in the array!

If size is known at compile time, this can be rewritten as:

std::array<int*, size> arr;
arr[i] = &val;

No need to delete, and it checks overflows.

If size is unknown at compile time, you can do:

std::vector<int*> arr;
arr.resize(size);
arr[i] = &val;

Upvotes: 0

M.M
M.M

Reputation: 141544

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.

Upvotes: 4

Related Questions