Search code examples
c++pointersnew-operator

New operator outside main function - C++


Why this code is working:

 //Things
 int **A;

 main(){

    //things
    A = new int*[n];
    for (int i = 0; i < n; i++) {
        A[i] = new int[m];
        }
   // things
}

And this code isn't working:

//Things
int **A;

void functionOutsideMain(int **A,int n, int m){
    A = new int*[n];
    for (int i = 0; i < n; i++) {
        A[i] = new int[m];
        }
    }

main(){

//Things
functionOutsideMain(A,n,m);
//Things
}

When I use new operator outside main function in a separate function it won't work.

But if I use new operator inside main funcion it works.

Can you explain me why this is happening?

or

If I'm doing something wrong.


Solution

  • In the first example, A is just a global variable, which main() uses directly.

    In the second example, functionOutsideMain() has its own A parameter which it uses, whereas main() still uses the global A variable instead.

    functionOutsideMain() takes its A parameter by value. When main() passes in the global A variable to functionOutsideMain(), a copy of that A is made, and so any value that functionOutsideMain() assigns to its A parameter will not be applied to the global A variable, which is why main() does not see the change.

    To do what you are attempting, you need to have functionOutsideMain() take its A parameter by reference instead:

    void functionOutsideMain(int** &A, int n, int m)
    

    Now, any value functionOutsideMain() assigns to its A parameter will be assigned to the global A variable, and thus will be seen by main().