c++ - How do you dynamically expand array and update? -


i trying wrap head around how logic works. idea dynamically allocate memory because won't know how many iterations program go through , can't use vectors. here abstraction of have far. have while loop contains variable count act size of array. update stored in array. thing can't figure out how update array ipoint without making infinite amount of if else statements. know there better way @ point brain fried.

#include <iostream> #include <string>   using namespace std;   int main() {      int itickets, count = 0, update = 0;     int *tempipoint = null;     int *ipoint = null;          {         count++;         update++;           if (count == 1)         {               tempipoint = new int[count];             (int = 0; < count; i++)             {                 *(tempipoint + i) = update;             }          }         else if (count > 1)         {               ipoint = new int[count];             (int = 0; < count; i++)             {                 *(ipoint + i) = *(tempipoint + i);              }             *(ipoint + count) = update;           }      } while (count != 10);     (int = 0; < count; i++)     {         cout << *(ipoint + i); }     delete[] tempipoint;     delete[] ipoint;     return 0; } 

every time loop iterates, need to:

  1. free tempipoint's memory, dynamically allocated in previous iteration.
  2. reallocate ipoint's current size.
  3. copy ipoint's data tempipoint.
  4. free ipoint's memory , reallocate new size.
  5. copy tempipoint's data ipoint , add new value end of ipoint.

also, note *(ipoint + count) equivalent ipoint[count] (and syntax should using).

this appears homework i'm leaving implementation you.

a far better , simpler solution (pointed out in comments ben voigt) have tempipoint point ipoint's memory, reallocate ipoint, transfer data ipoint using tempipoint , free memory.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -