-1

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:

enter image description here

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;
}
timmyspan
  • 77
  • 1
  • 11
  • When you use dynamic memory allocation, you don't control the address of the allocated memory. That is under the control of the implementation of the memory allocator. Why would you care? There is usually no way and no reason to do this. – Avi Berger Sep 12 '16 at 03:43
  • You don't have much control over what is returned by `new`. Is this homework? Are you sure you're not just supposed to add a couple of `delete` statements? – 001 Sep 12 '16 at 03:43
  • It is homework @JohnnyMopp There's commented out lines but I can't find out what to do there – timmyspan Sep 12 '16 at 03:45
  • If this is homework, then you are misunderstanding what the assignment is. Perhaps you were asked to use the same pointer variable (which will remain at the same address, unlike the reallocated dynamic memory). – Avi Berger Sep 12 '16 at 03:50
  • I changed the post to include the output I should receive @JohnnyMopp and I'm just really confused by this – timmyspan Sep 12 '16 at 03:54
  • @timmyspan It would help if you posted the code without all of those `cout` statements and comments. Everyone willing to help already knows what `new[]` and `delete[]` do, and the `cout` statements do nothing except add clutter to the code making it more difficult to read. – PaulMcKenzie Sep 12 '16 at 04:10
  • But I add the pointers after those statements to find the addresses and maybe those need to be changed as well @PaulMcKenzie – timmyspan Sep 12 '16 at 04:12
  • For the sake of anyone trying to help, [here is your code](http://ideone.com/IW39Mj). That looks much more readable. – PaulMcKenzie Sep 12 '16 at 04:13
  • Given what your entire post boils down to, without the comments and cout statements, I see nothing wrong *except* that you didn't issue a `delete [] nArray;` before the exit of the `main` function. So what are you really trying to accomplish? – PaulMcKenzie Sep 12 '16 at 04:16
  • I'm trying to accomplish 8 identical addresses. The picture in my OP shows what I need to see and I am getting the top 5 addresses identical but the bottom 3 I don't know what to do in order for them to be identical to the top 5 – timmyspan Sep 12 '16 at 04:18
  • @timmyspan -- What is the **high-level** goal you're trying to accomplish? You have a "dynamic array", and you resize it by allocating new space, copying the old data to the new space, delete the old space, and assign the pointer to the new space. That is exactly what you're supposed to do. I really don't want to be flippant, but your explanation of what you want to do doesn't make any sense whatsoever (8 identical addresses, 3 addresses being different than 5 others, ???) – PaulMcKenzie Sep 12 '16 at 04:21
  • I'm so new that I can't really explain the end goal. My professor just wants that picture to be my output and have all addresses with the same value as when we first initialized the array, even the new space we assigned the pointer to – timmyspan Sep 12 '16 at 04:24
  • You 1) Alloc `nArray`. 2) Alloc `aux`. 3) `delete nArray`. 4) Have `nArray = aux`. There's no way nArray will now point to the same location it used to since `nArray` and `aux` exist at the same time. – 001 Sep 12 '16 at 04:26
  • @timmyspan -- You have no control over what the address will be if you resize a dynamically allocated area to a size larger than the original. Even the low-level `C` function `realloc` cannot guarantee this. You definitely are not reading or understanding the assignment (I'm giving the teacher the benefit of the doubt). – PaulMcKenzie Sep 12 '16 at 04:26
  • Well what my code should look like is the picture shared in my OP, I have read it multiple times. That picture is the output to receive a 100% I have no control if you find it confusing or not. @PaulMcKenzie – timmyspan Sep 12 '16 at 04:51
  • 1
    It doesn't matter what you want your code to look like. You can't resize an array to a larger size, and guarantee you get the same addresses -- plain and simple. The only way you can achieve anything like this is to write a class that *reserves* memory to serve as a "capacity", but logically keeps the number of actual items that can be used, similar to `std::vector`. But even then, a `std::vector` cannot guarantee the same pointers if you resize it larger than then capacity. – PaulMcKenzie Sep 12 '16 at 04:54
  • It does when I want an A @PaulMcKenzie – timmyspan Sep 12 '16 at 05:05
  • Well, you're being cheated or having a joke pulled on you. I don't know what else to tell you. The C++ language isn't going to change because you want an 'A' – PaulMcKenzie Sep 12 '16 at 05:09
  • I guess I am being cheated then. Thanks for your help – timmyspan Sep 12 '16 at 05:14
  • Are you sure same value is required by your assignment? It could be just co-oncidence in the example output. Though with some trickery and trial and error, you could get the same value for the 2nd new reliably, for the particular OS and compiler. However, that would not be part of a C++ course, it would be part of something like "operating system programming" course. – hyde Sep 12 '16 at 09:24

3 Answers3

1

There isn't ++ a way to actually reallocate a vector in C++. So what you do is:

  1. allocate a new vector with a higher size - store the pointer in aux
  2. copy the old nArray content in the content of aux
  3. delete[] the nArray vector
  4. assign aux to the nArray vector

like

// 1,
int* aux=new int[arraySize+2];
// 2.
// deliberately simple here
for(size_t i=0; i<arraySize; i++) {
  aux[i]=nArray[i];
}
// 3.
delete[] nArray; // the entire memory occupied bu nArray is recycled
// 4.
nArray=aux; // make nArray point to the newly allocated chunck

// supplementary, adjust the arraySize, as it is now larger by 2
// scratch that, the rest of the code works afterwards using arraySize + 2
// arraySize += 2;

Or, as Stroustrup recommends use the std::vector.


fnote ++ for some values of "isn't" - see the linked

Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23
  • that seemed to work and I have 3 locations right now! So to get the other locations to match up I am not too sure how to do that. This is my first C++ class – timmyspan Sep 12 '16 at 04:00
  • "I have 3 locations right now!" what do you mean by "locations"? – Adrian Colomitchi Sep 12 '16 at 04:03
  • Sorry, in the picture I need 8 memory addresses to be the same. I entered your code in and now I have 5 out of 8. After reinitializing I am getting different addresses. I edited my code to show where I placed your code @AdrianColomitchi – timmyspan Sep 12 '16 at 04:07
  • Nope, cannot be done. There are no warranties that, no matter what happens, after a rellocation you will get the same address. – Adrian Colomitchi Sep 12 '16 at 04:13
  • Well, somehow my Professor got them to all be the same so I don't know what he did. Thanks though for helping me get closer. – timmyspan Sep 12 '16 at 04:16
  • There are ways in which sometimes he can get it to be the same, but not guaranteed that it will happen all the times, If you really-really want to know, read about `malloc`, `realloc` and `free` (google for them) but keep in mind that those are functions from C rather than C++. – Adrian Colomitchi Sep 12 '16 at 05:25
1

You can reuse the same location with "placement new"

An example upon your example could be:

//**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()
{
    int reserved[arraySize+2]; // pre allocated enough memory

    cout << endl << endl;
    int* nArray = new (reserved) int[arraySize]; // placement new place nArray at "reserved" location
    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
    // Well, not now.
    cout << endl << "  --->Before reallocating memory for nArray." << endl;
    cout << "  nArray address is <" << nArray << "> and contains the value " << hex << *nArray << endl;
    int* aux = new (reserved) int[arraySize + 2]; // and again, placement new place aux at "reserved" location
    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; // you can't do this now
    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-------------
//----------------------------------
Loreto
  • 674
  • 6
  • 20
0

To delete a array you must do: delete[] nArray;

Jhon Pedroza
  • 698
  • 6
  • 13