1

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 ?

Leo
  • 25
  • 2
  • Remember that arguments are passed *by value*, which means the value of the expression in the call is copied into functions local argument variable. In `function1` and `function2` the variable `A` is a local copy, and if you modify it like you do in `function1` that modification will be lost when the function returns and the life-time of the variable ends. This should be mentioned and perhaps even showcased in any decent [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), tutorial or class. – Some programmer dude Mar 24 '21 at 15:33

1 Answers1

0

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185