Dynamic allocation to array of pointers and its alternatives

1.5k views Asked by At

The standard way of allocating array using new int is:

 int* arr = new int[50];

while declaring it in this manner there is going to be contiguous memory allocation and there will be a single array variable in the stack of variables.

if I want to declare it in the form of 50 different pointer variables so that each pointer would have different memory address and not necessarily contiguous the most obvious way of going for it is like this:

int * arr[50];

but in this way what would be the command / code for assigning memory ( i.e. via new int ) and what are the downsides or advantages of declaring in each manner.

2

There are 2 answers

5
nishantsingh On BEST ANSWER

The obvious way would be to iterate over all the elements and allocate memory for them:

for (int i = 0; i < 50; i++){
    arr[i] = new int;
}

The downside of non-contiguous memory chunk would be cache misses. You can read more on that here.

2
iammilind On

How to assign, is already mentioned in this answer; Hence not repeating.
For single int allocation, your below line is an overkill:

int* arr[50];  // all downsides only

Instead of that, you should use simple integers:

int arr[50];

Better to utilise facilities by standard containers such as:

std::vector<int> vi;  // if the number of int-s are dynamic
std::array<int, 50> ai; // if the number of int-s are fixed

Finally, from this answer,

"Avoid pointers until you can't... So the rule of thumb is to use pointers only if there is no other choice."