I'm in the process of teaching myself C++ and am currently learning about dynamically allocating memory. Here's the code that I'm currently working with:
#include <iostream>
using namespace std;
int *memAdd(int* dyn_Point, int *lenPoint){
int *new_Dyn_Point = new int[*lenPoint * 2];
*lenPoint = *lenPoint * 2;
for(int i = 0; i < *lenPoint; i++){
new_Dyn_Point[i] = dyn_Point[i];
}
delete lenPoint;
delete[] dyn_Point;
return new_Dyn_Point;
}
int main(){
int len = 2;
int *lenPoint = &len;
int current = 0;
int val;
int *dyn_Point = new int[len];
cout << "Input a value for point 1: ";
cin >> val;
dyn_Point[current] = val;
while(val > 0){
current++;
cout << "Input a value for point " << current+1 <<" (0 to exit): ";
cin >> val;
if(current+1 == len){
*dyn_Point = *memAdd(dyn_Point, lenPoint);
cout << len;
}
dyn_Point[current] = val;
}
for(int i = 0; i < len; i++){
cout << &dyn_Point[i] << "\n";
cout << dyn_Point[i] << "\n\n";
}
delete[] dyn_Point;
}
My Question: When adding more memory does it have to increment by a certain value?
Whenever I start with a value in my "len" variable that's not 2 my program will crash either as soon as I try and allocate more memory or after more memory has been allocated and even more has to be added a second time.
Is this how it's supposed to be or am I missing something entirely here?