Function does not change passed pointer C++

前端 未结 4 495
北海茫月
北海茫月 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:30

    Because you are passing a copy of pointer. To change the pointer you need something like this:

    void foo(int **ptr) //pointer to pointer
    {
        *ptr = new int[10]; //just for example, use RAII in a real world
    }
    

    or

    void bar(int *& ptr) //reference to pointer (a bit confusing look)
    {
        ptr = new int[10];
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 02:46

    You cannot change the pointer unless you pass it by (non const) reference or as a double pointer. Passing by value makes a copy of the object and any changes to the object are made to the copy, not the object. You can change the object that the pointer points to, but not the pointer itself if you pass by value.

    Have a read of this question to help understand the differences in more detail When to pass by reference and when to pass by pointer in C++?

    0 讨论(0)
  • 2020-11-22 02:47

    You are passing the pointer by value.

    Pass a reference to the pointer if you want it updated.

    bool clickOnBubble(sf::Vector2i& mousePos, std::vector<Bubble *> bubbles, Bubble *& t)
    
    0 讨论(0)
提交回复
热议问题