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:
- free
tempipoint's memory, dynamically allocated in previous iteration. - reallocate
ipoint's current size. - copy
ipoint's datatempipoint. - free
ipoint's memory , reallocate new size. - copy
tempipoint's dataipoint, add new value end ofipoint.
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
Post a Comment