-4

I am learning C++ and have a problem with pointers. I want to pass a pointer into my method and assign it a new value. But my pointer is 0 after the method was called. What am I doing wrong? Thanks

#include <iostream>

using namespace std;

class MyObject
{
    public:
        bool search(int* a) 
        {
            int* test = new int(23);
            a = test;
            return true;
        }
};


MyObject* obj;

void search()
{
    int* test = NULL;
    obj->search(test);
    cout << test << endl;
}

int main(int argc, char *argv[])
{
    obj = new MyObject();
    search();
}
user4581301
  • 29,019
  • 5
  • 26
  • 45
  • @StaticBeagle None of the answers there seem to show how to pass a reference to a pointer. I'm not sure it's a good duplicate. – Barmar Jun 01 '18 at 05:11
  • Unrelated: Consider making `obj` an automatic variable inside `main` and passing it into `search` as a parameter. Global variables are not strictly bad, but they can make your life harder than it needs to be as your programs grow more complex.. – user4581301 Jun 01 '18 at 05:23
  • @rwp that code is only C if agajvery is using some really impressive macros. – user4581301 Jun 01 '18 at 06:14

3 Answers3

3

You need to pass the pointer by reference.

bool search(int*& a)

Without this, the pointer is passed by value, and you are only assigning a copy of what you passed. To assign the actual object/variable you pass, you need to pass the pointer by reference.

For further reading: What's the difference between passing by reference vs. passing by value?

Longarmx
  • 101
  • 1
  • 1
  • 4
0

a is a local variable, if you set its value during the search method execution, it won't have any effect on the test variable in the free search function, because a is just a copy of test.

You should pass a by reference:

bool search(int *&a) { 
    int* test = new int(23);
    a = test; 
    return true; 
}
tttapa
  • 1,199
  • 7
  • 21
0

The pointer was passed by value instead of reference. Which means the local variable test's value was not changed.

Instead do bool search(int*& a)

This will pass the reference to the method, which will update the local variable in the calling function.

Destructor
  • 473
  • 1
  • 3
  • 12