Search code examples
c++arrayspointersmemory-managementdynamic-allocation

Dynamic allocation to array of pointers and its alternatives


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.


Solution

  • 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.