how to check pointer to class object for null value

This is jamming me up a little bit. I've been thru the tutorial on this site but the bit about null pointers I apparently don't get.. Thanks in advance for any advice and suggestions

My question is.. lets say I have a pointer p_unit of type c_unit* (c_unit is an a.b.c.)
I have a function that returns a pointer to a new c_unit object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
c_unit * man_add_unit()
{
    c_unit * local_p_unit;
    unsigned short int local_run_code;
    print_man_add_menu();
    local_run_code = get_a_run_code(); // this bit just gets user input

    switch (local_run_code)
    {
    case 1:
        local_p_unit = add_matl_unit();
        break;
    case 2:
        local_p_unit = add_indy_unit();
        break;
    // ...
    }
    return local_p_unit;
}

I assign that to p_unit, then add it to a vector v_units:

1
2
3
p_unit = man_add_unit();
v_units.push_back(p_unit);
cout << "New unit added.\n";


The whole program runs on a loop, and another thing the user can do is to print out data on c_unit objects pointed to by v_units. The problem is, in that function up there ^ I give the user the option to go back to main menu without creating a unit.

Since "local_p_unit" is declared but not assigned an initial value, I'm guessing the function would return a "null" pointer (which is what's hanging me up). If I just let this run with the above code, and go to print out the unit data, the program crashes.

I tried to make an if thing with p_unit == 0
but this always returns false and doesn't catch the "bad" unit that will subsequently cause a crash. Can someone please point me in the right direction here?

Btw, I have considered assigning a reference to a generic c_unit object to that there local_p_unit so it won't return null, then remove pointers to that object from v_units at the end of the loop.. But I know there's got to be a better way.

Thanks for any help yall can give me
- cPlusN00b
Last edited on
-
Last edited on
update: HELP want to cheat on assignment will give $15 to anyone who will f*** my professor's mom. (maybe this is how to get attention on this forum?)
ok hey someone helped me, how can I remove this post so it's not a duplicate?
don't worry about it. Just leave it and let it fade out naturally.

In case anyone stumbles on the thread... the question was answered here:
http://cplusplus.com/forum/general/92579/
thanks :3
Topic archived. No new replies allowed.