12.2.4 Pointer to Null

An unassigned pointer points to random memory. So how do you make an ‘empty’ pointer, pointing to nothing? You assign a ‘null’ address. We also call this a ‘null pointer’.

 
int * p1 = null;  

You could now rewrite the code at the beginning of this chapter. Remember, the whole problem was that we could not return a name when none was found.

 
class players { 
  Memc<Player> list; 
 
  // no problem with references here 
5  Circle &  add(Vec2 & pos, Str & name) { 
    Player & p = list.add(); 
    p.set(pos, name); 
    return p; 
  } 
10 
  // a pointer is used instead of a reference 
  Circle * findByName(Str & name) { 
    FREPA(list) { 
      if(Equal(list[i].getName(), name) { 
15        return &list[i]; // notice the ampersand! 
      } 
    } 
    // no player found with this name 
    return null; 
20  } 
} 
// globaal object 
players Players; 
 
25// somewhere in your application 
Players.add(Vec2(1,1), ”niceGuy”); 
player * friend = Players.findByName(”coolGuy”); 
 
// check if the player exists 
30if(friend != null) { 
  Greet(friend); 
}  

When no player is found with a certain name, a null pointer will be returned. By checking if the returned value is different from null, we make sure the Greet(player * p) function is only executed with a valid player.

Note
Some memory containers (like Memb) will move their objects around when the container grows. When there isn’t enough memory in the current container, the whole container will be moved to a new memory location. This means that pointers to members of that container become invalid. If you need pointers to stay valid, use a container like Memx. Otherwise, only create pointers local to a method.