Search code examples
c++arraysmultidimensional-arraydynamic-allocation

Dynamic allocation of 2D array in c++


So I define the pointer x pointing to n integers as:

int* x = new int [n];

Values of x change in a loop. In the end of the loop I store the pointer x in a 2D pointer y that has been initialized as:

int** y = new int* [n];

I use the following assignment expression to store the pointer to x in the ith element of y:

y[i] = x;

Since x points to the same part of the memory but the values stored in x keep changing, all the elements in 2D array y will get the last values that have been stored in x during the last execution of the loop.

My question:

Is there anyway I can unlink the x from where it has been pointing and make it point to a new part of the memory every time I store its address in y? This way y stores the address to different parts of the memory hence the history of answers stored in x can be retrieved. Also please let me know if this method (if at all possible) is faster than filling up the rows of y with x in each iteration by looping over its elements.


Solution

  • If my understanding is correct, you want to keep the history of all the values of the array x inside y.

    What are you suggesting isn't really possible without filling up the rows of y with x in each iteration.

    What you can do is preallocate so you don't have the new allocation inside the loop, you have it before the loop (you will still do a copy thou).

    The cost of memory will still be n^2, and so will be the complexity.

      // without preallocation
      {
         int** y = new int*[n];
         int* oldx=0;
         for (int i=0;i<n;i++)
         {
            int* x = new int[n];
            // migrate old values in case you are modifying just a part of x
            if (oldx!=0)
            {
                memcpy(x,oldx,n*sizeof(int));
            }
            //... do some stuff with x;
            y[i] = x;
            // keep reference to copy in next iteration
            oldx=x;
         }
      }
    
      // with preallocation
      {
         int ** y = new int*[n];
         // preallocate memory
         for (int i=0;i<n;i++)
         {
             y[i] = new int[n];
         }
         int* oldx=0;
         for (int i=0;i<n;i++)
         {
    
             int* x =y[i];
             // migrate old values in case you are modifying just a part of x
             if (oldx!=0)
             {
                 memcpy(x,oldx,n-sizeof(int));
             }
             // ... do stuff with x
             // keep reference to copy in next iteration
             oldx = x;
         }
      }