I'm trying to initialize an array and then reallocate the memory to the same address. Here's my code:
//**begin #include files************
#include <iostream> // provides access to cin and cout
//--end of #include files-----------
//----------------------------------
using namespace std;
//----------------------------------
//**begin global constants**********
const int arraySize = 5;
//--end of global constants---------
//----------------------------------
//**begin main program**************
int main()
{
cout << endl << endl;
int* nArray = new int[arraySize];
cout << " --->After creating and allocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
for (int i = 0; i < arraySize; i++)
{
nArray[i] = i*i;
}
cout << " --->After initializing nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
for (int i = 0; i < arraySize; i++)
{
cout << " nArray[" << i << "] = " << nArray[i] << " at address <" << nArray + i << ">" << endl;
}
// You'll need a command here to fix the memory leak
cout << endl << " --->Before reallocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << endl;
int* aux = new int[arraySize + 2];
cout << dec << " --->After reallocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
for (int i = 0; i<arraySize; i++) {
aux[i] = nArray[i];
}
delete[] nArray;
nArray = aux;
cout << endl << " --->After reinitializing nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
for (int i = 0; i < arraySize + 2; i++)
{
cout << " nArray[" << i << "] = " << nArray[i] << " at address <" << nArray + i << ">" << endl;
}
// . . . and also here.
cout << endl << " --->Getting ready to close down the program." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
// Wait for user input to close program when debugging.
cin.get();
return 0;
}
//--end of main program-------------
//----------------------------------
I've tried using delete nArray; then initializing again but it doesn't work. Not sure what to do but I've searched for a couple of hours and any help would be appreciated!
The commented lines show where statements should be added.
This is the result I need:
const int arraySize = 5;
int main()
{
int* nArray = new int[arraySize];
for (int i = 0; i < arraySize; i++)
nArray[i] = i*i;
int* aux = new int[arraySize + 2];
for (int i = 0; i<arraySize; i++)
aux[i] = nArray[i];
delete[] nArray;
nArray = aux;
}