Null pointer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
struct mystruct{
    int n;
};
class mscope{
    public:
        std::vector<mystruct> mv;

        bool find_struct(int n, mystruct *pm){
            std::vector<mystruct>::iterator mit;
            for(mit = mv.begin(); mit != mv.end(); ++mit){
                if(mit->n == n){
                    pm = &(*mit);
                    std::cout << "found match" << std::endl;
                    return true;
                }
            }
            return false;
        }
};
int main()
{
    mystruct *pm;
    mscope *ms = new mscope();
    for(int i=1; i<6; i++){
        ms->mv.push_back(mystruct());
        mystruct *m = &(ms->mv.back());
        m->n = i;
    }

    ms->find_struct(2, pm);
    if(!pm){
        std::cout << "pointer is null" << std::endl;
        delete ms;
        return 0;
    }

    std::cout << pm->n << std::endl;

    delete ms;

    return 0;
}


Hello. So I have a vector of structs and I want to traverse it, find a struct that matches a constraint and obtain a pointer to that struct. I made a function for this purpose which takes a number and an empty pointer that will store the reference. However, after function returns the pointer becomes null.

What could be causing this?
try this
bool find_struct(int n, mystruct *&pm){
Last edited on
The problem is that you are passing the pointer into your function by value.

If you want your function to modify the pointer in a way that is reflected in the calling code, you need to pass it by reference - just as you would for any other type of argument.
Topic archived. No new replies allowed.