-5

So the problem is I have a function for example

int * fun2(){...}

int fun(int *a)
{
   a = fun2(); // this is like line never exist
}

I want to assign returned pointer by fun2 to pointer a and it doesnt happen WHY?

And an "a" variable has already a value, before assigning fun2(), but I dont think so it really matter.

  • How are you testing whether or not it happens? – Chuck Dec 29 '13 at 19:31
  • If you are asking "why does `a` still have the old value after I call `fun(a)`, see [this question](http://stackoverflow.com/questions/4426474/is-passing-pointer-argument-pass-by-value-in-c). – DCoder Dec 29 '13 at 19:32

4 Answers4

1

It does work. It changes the value of a in the local scope.

If you want to see change outside of fun, you have to pass a reference: int fun(int *&a).

(Note: you have to provide us a complete example which demonstrates your problem, so we don't have to do educated guesses).

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1

Your a is a temporary object in fun(). I fyou want fun() to change the pointer to a you'll need to take the pointer as reference:

int fun(int*& a) {
    a = fun2();
}

Note that this interface is probably severely broken.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

Another alternative is to pass the address of the a pointer variable:

int fun(int **a)
{
  *a = func2();
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

You passed the pointer by value. Inside the function, it's a new copy of that pointer. You change only the copy in there.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055