Search code examples
c++pointersnew-operatorallocationmemory-address

Why can I not to readdress pointer within an outer function in C++?


I have a simple code:

void function1(int* A);
void function2(int* A);

int main(int argc, char* argv[]) {

    int* A = new int[4];
    // Readdressed into function1: A[0] is preserved
    A[0] = 21;
    function1(A);
    cout << "\nA[0] is: " << A[0];
    // Result A[0] = 21

    // Is not readdressed into function2: A[0] is not preserved
    A[0] = 21;
    function2(A);
    cout << "\nA[0] is: " << A[0];
    // Result A[0] = 23

    return 0;
}

void function1(int* A) {
    A = new int[4];
    A[0] = 23;
}
void function2(int* A) {
    A[0] = 23;
}

Output:

In the case of function1 output A[0] is 21

In the case of function2 output A[0] is 23

Question: Why does A-pointer not get (In the first case) an address to a new allocated memory cells where A[0] is 23, and preserve an address where A[0] is 21 instead ?


Solution

  • Unless you pass a reference, parameters are passed by value. Pointers are no different.

    void function1(int* A) {
        A = new int[4];
        A[0] = 23;
    }
    void function2(int* A) {
        A[0] = 23;
    }
    

    function1 assigns a new value to A. However, A is a local variable in function1. Assining 23 to the first element of that new array, does not affect the array A was originally pointing to.

    function2 gets A passed by value as well. Though, it does not attempt to modify A. It just uses A to write 23 at the adress pointed to by A.


    Consider this example which is similar to your function1:

    #include <iostream>
    
    
    int a,b = 0;
    
    void function1(int* p) {
        p = &b;
        *p = 42;
    }
    
    int main() {
        std::cout << a << b << "\n";
        int* ptr = &a;
        function1(ptr);
        std::cout << a << b << *ptr << "\n";
    }
    

    Output is

    00 
    0420
    

    because after calling function1 ptr in main still points to a. The p = &b; in function1 only affects p which is local to function1.