hehe, got bored doing nothing while waiting for replies for this post, so I scavenged the net for answers to these questions.
And indeed I found a lot.
1.) NEW is not a C++ function but an operator.
2.) There is no C++ counterpart for C's REALLOC function
with info I found stated in 2, I asked myself again, "So, how does one reallocate a memory allocated previously using NEW?".
Again, I asked the mighty GOOGLE for the answers. GOOGLE didn't failed me, and gave me several answers but I will post only the first one (but not necessarily the best or least).
Cant explain the code better than the page where I got this code, so just visit this page using this URL for the explanations encase the comments in the following codes below is not enought :). So here's the code:
by the way, before the code, let me credit the page where I got the codes :). I got it from this page :)
http://www.fredosaurus.com/notes-cpp/newdelete/55dynexample.html
so finally the codes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int max = 10; // no longer const
int* a = new int[max]; // allocated on heap
int n = 0;
//--- Read into the array
while (cin >> a[n]) {
n++;
if (n >= max) {
max = max * 2; // double the previous size
int* temp = new int[max]; // create new bigger array.
for (int i=0; i<n; i++) {
temp[i] = a[i]; // copy values to new array.
}
delete [] a; // free old array memory.
a = temp; // now a points to new array.
}
}
//--- Write out the array etc.
| |
the code is not complete but I know that you know how to complete it :)
Just encase you dont, just drop a line here and I will be more than willing to help you with it :)
Go Cplusplus.com !!!!! :)