Erick.1993
Erick.1993

Reputation: 63

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.

Upvotes: 0

Views: 411

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596332

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().

Upvotes: 1

shirish
shirish

Reputation: 678

Hey I didn't get what you meant by not working, but the possible solutions to the problems could be

  • No need to pass A again to functionOutsideMain since A is already global

  • When you pass A to functionOutsideMain, the actual parameter A becomes the formal parameter A, and now here's the problem, in C there is only pass by value(unlike pass by reference in C++). So when you pass A to the function, a new pointer gets created in the function and when you allocate a chunk of memory to it, the new pointer points to that memory and not the old pointer that you are using in main function.

One possible solution for this would be

void function_outside_main(int ***A, int n, int m) {
    int **Aptr = (*A);
    // And then use Aptr to allocate memory as you did
}


Else don't pass A as function parameter since it's a global variable

Upvotes: 0

Related Questions