Function does not change passed pointer C++

前端 未结 4 510
北海茫月
北海茫月 2020-11-22 01:58

I have my function and I am filling targetBubble there, but it is not filled after calling this function, but I know it was filled in this function because I ha

4条回答
  •  时光说笑
    2020-11-22 02:40

    if you write

    int b = 0;
    foo(b);
    
    int foo(int a)
    {
      a = 1;
    }
    

    you do not change 'b' because a is a copy of b

    if you want to change b you would need to pass the address of b

    int b = 0;
    foo(&b);
    
    int foo(int *a)
    {
      *a = 1;
    }
    

    same goes for pointers:

    int* b = 0;
    foo(b);
    
    int foo(int* a)
    {
      a = malloc(10);  // here you are just changing 
                       // what the copy of b is pointing to, 
                       // not what b is pointing to
    }
    

    so to change where b points to pass the address:

    int* b = 0;
    foo(&b);
    
    int foo(int** a)
    {
      *a = 1;  // here you changing what b is pointing to
    }
    

    hth

提交回复
热议问题