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. I've already posted in the beginner forum but haven't got a response.
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:
c_unit * man_add_unit()
c_unit * local_p_unit;
unsigned short int local_run_code;
local_run_code = get_a_run_code(); // this bit just gets user input
local_p_unit = add_matl_unit();
local_p_unit = add_indy_unit();
I assign that to p_unit, then add it to a vector v_units:
p_unit = man_add_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