c++ - How to increase the number of cells in an array with Dynamic Allocation? -


so trying use dynamic allocation increase number of cells in array.

the array type location created includes x , y coordination

the process goes way:

  1. i create new heap location array of same size + 1
  2. i use for-loop copy previous locations new array
  3. deleting previous pointer
  4. pointing previous 1 new one

what doing wrong?

this code :

void extendlocarray(location** ilocprevarray, int innumberofmovements) {     // variable definition     location* locnewpatharray = new location[innumberofmovements];     int       nindex;      // code section      // copies previous locations     (nindex = innumberofmovements - 2; nindex >= 0; nindex--)     {         locnewpatharray[nindex] = (*ilocprevarray)[nindex];     }      delete[](*ilocprevarray);      (*ilocprevarray) = locnewpatharray; } 

a correct function can following way (provided want copy elements of arrays in reverse order)

void extendlocarray( location** ilocprevarray, size_t innumberofmovements ) {     // variable definition     location* locnewpatharray = new location[innumberofmovements];      // copies previous locations     ( size_t = innumberofmovements - 1; != 0; i-- )     {         locnewpatharray[i-1] = ( *ilocprevarray )[i-1];     }      delete [] *ilocprevarray;      *ilocprevarray = locnewpatharray; } 

you declare function like

void extendlocarray( location * &ilocprevarray, size_t innumberofmovements ); 

that use reference pointer.

here demonstrative program used typedef name location program compile.

#include <iostream>  // simplified definition of location typedef int location;  void extendlocarray( location** ilocprevarray, size_t innumberofmovements ) {     // variable definition     location* locnewpatharray = new location[innumberofmovements];      // copies previous locations     ( size_t = innumberofmovements - 1; != 0; i-- )     {         locnewpatharray[i-1] = ( *ilocprevarray )[i-1];     }      delete [] *ilocprevarray;      *ilocprevarray = locnewpatharray; }  int main()  {     const size_t n = 10;     location *p = nullptr;      ( size_t = 0; < n; i++ )     {         extendlocarray( &p, + 1 );         p[i] = i;     }      ( size_t = 0; < n; i++ ) std::cout << p[i] << ' ';     std::cout << std::endl;      delete [] p;      return 0; } 

the program output is

0 1 2 3 4 5 6 7 8 9 

take account instead of writing loop use standard algorithm std::copy_backward declared in header <algorithm>. example

#include <algorithm>  //... std::copy_backward( *ilocprevarray,                      *ilocprevarray + innumberofmovements - 1,                      locnewpatharray + innumberofmovements - 1 );     

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -