3

I have a problem with passing an array to a function and then modifying it. For example:

void foo(int ** a) {
  int * b = new int[3]
  //Initialize b, i.e b = {3, 2, 1}
  a = &b;
  //*a = {3, 2, 1}
}

int * c = new int[3]
//Initialize c; c = {1, 2, 3}
foo(&c);
// c is still {1, 2, 3}. Why?

I'm not really sure why c doesn't point to the same array as b.

  • 4
    `*a = b;` Should work. Though I am not sure what you are trying to do. – Arunmu Jul 05 '16 at 13:39
  • @Arunmu Yea that works, thanks. – Marko Stojanovic Jul 05 '16 at 13:53
  • @MarkoStojanovic Your question is little similar to the behavior explained in [this](http://stackoverflow.com/questions/4776010/pass-by-reference-and-value-with-pointers) question so it will also help you understand your problem :) – Itban Saeed Jul 05 '16 at 14:00
  • @ItbanSaeed Yes, I was looking for exactly that, but didn't find it myself. I guess I didn't know how to form the statement properly when googling. – Marko Stojanovic Jul 05 '16 at 14:07
  • its no problem, there is no rocket science in googling. You might have not reached the link from the results.. I just thought about making your issue little more clear :) – Itban Saeed Jul 05 '16 at 14:13

1 Answers1

5

a has type int** and it's passed by value, so modifying it does not modify c.

To modify it, you have to do this:

  *a = b;

By doing this, you assign the address of b to the variable pointed by *a (which corresponds to c), so they will point to the same array.

Mattia F.
  • 1,590
  • 8
  • 17