0

I found a function to resize an array and am having trouble understanding how it works (or if it's working properly). For testing I set the "temp" array to a new value and "startCounter" does get assigned to that value, however the memory location for startCounter doesn't change. Here is my code:

int * startCounter;


void resizeArray(int *&arraySent,int origSize,int newSize) {
    output << "&arraySent " << &arraySent << endl;
    output << "arraySent[0] " << arraySent[0] << endl;
    int* temp = new int[newSize];
    output << "&temp " << &temp << endl;
    for (int i=0; i<origSize; i++) {
        temp[i] = arraySent[i];
    }
    temp[0]=744;
    delete [] arraySent;
    arraySent = temp;
    output << "&arraySent " << &arraySent << endl;
}

//....

startCounter = new int [3];
startCounter[0]=345;
output << &startCounter << endl;
resizeArray(startCounter,3,10);
output << "startCounter[0]" << startCounter[0] << endl;
output << "&startCounter" << &startCounter << endl;

Here is the output I get from this:

    &startCounter 0x60fab8
    &arraySent 0x60fab8
    arraySent[0] 345
    &temp 0x82cfe54
    &arraySent 0x60fab8
    startCounter[0] 744
    &startCounter 0x60fab8

My question is, why does the memory location of startCounter not change from 0x60fab8 after deleting it and assigning it to the new "temp" array? Shouldn't it now become 0x82cfe54?

P.S. I understand about vectors and such but am mainly concerned with understanding how this particular function works.

0

2 Answers 2

2
void resizeArray(int *&arraySent,int origSize,int newSize) {
    output << "&arraySent " << &arraySent << endl;

outputs the address of the pointer variable, not the address that it holds.

simply omit the address operator to get the (probably) intended effect

Sign up to request clarification or add additional context in comments.

Comments

1

&startCounter is the address of the pointer, not the address it points to. it's value won't change. simply use startCounter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.