简体   繁体   中英

Dynamic allocation of 2D array in c++

So I define the pointer pointing to integers as: 整数的指针定义为:

int* x = new int [n];

Values of change in a loop. 值循环变化。 In the end of the loop I store the pointer in a 2D pointer that has been initialized as: 存储在已初始化为的2D指针中:

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

I use the following assignment expression to store the pointer to in the ith element of : 的指针存储在ith元素中:

y[i] = x;

Since points to the same part of the memory but the values stored in keep changing, all the elements in 2D array will get the last values that have been stored in during the last execution of the loop. 指向内存的同一部分,但是存储的值不断变化,因此2D数组所有元素将获得在最后执行循环期间存储在中的最后一个值。

:

Is there anyway I can unlink the from where it has been pointing and make it point to a new part of the memory every time I store its address in ? ,我都可以从其指向的位置断开链接并使其指向存储器的新部分吗? This way stores the address to different parts of the memory hence the history of answers stored in can be retrieved. 将地址存储到存储器的不同部分,因此可以检索存储在的答案的历史记录。 Also please let me know if this method (if at all possible) is faster than filling up the rows of with in each iteration by looping over its elements. 填充的行更快。

As for what is faster, I cannot say... I suggest you try and setup prototypes of each approach. As for re-linking x, you can use:

x = new int[n];

I hope this helps.

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;
     }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM