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.

5
  • 4
    *a = b; Should work. Though I am not sure what you are trying to do. Commented Jul 5, 2016 at 13:39
  • @Arunmu Yea that works, thanks. Commented Jul 5, 2016 at 13:53
  • @MarkoStojanovic Your question is little similar to the behavior explained in this question so it will also help you understand your problem :) Commented Jul 5, 2016 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. Commented Jul 5, 2016 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 :) Commented Jul 5, 2016 at 14:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I forgot that c's location is passed by value, so I thought *a = b and a = &b would be equivalent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.