It doesn't have anything to do with preventing you from urinating.
The scientific explanation:
Blackwell Synergy - J Sexual Medicine, Volume 2 Issue 6 Page 771-784, November 2005 (Article Abstract)
"Sleep-related erections have been reported to occur from the intrauterine life to senescence. It has been speculated that the main function of nocturnal erections is to provide adequate engorgement of the corpora cavernosa, which then leads to increased tissue oxygenation. This is in turn to prevent cavernous fibrosis, the histopathological basis for corporeal venoocclusive dysfunction, which probably is the most common cause of organic erectile dysfunction. It has been suggested that sleep-related erections are triggered by the release of nitric oxide by the nitrergic nerve fibers within the cavernous nerves. Androgens regulate this mechanism as well as some other non-nitrergic processes within the corpora cavernosa and within the central nervous system. By contrast, the erectile response to tactile or visual erotic stimuli in wakefulness predominantly involves an androgen-independent system, although it may, at least to a certain degree, also be influenced by androgen-sensitive mechanisms. No doubt, androgens are key players in the physiology of nocturnal erections, and the availability of new, user-friendly testosterone preparations such as transdermal gel and intramuscularly administered testosterone undecanoate stimulates further investigations on this field. The prospect that the quality of sleep may also be improved by an androgen therapy administered to improve sleep-related erections in hypogonadal men needs further basic research and appropriate clinical studies."
In layman's terms: it's normal and is supposed to happen, and if a man cannot get an erection for sex, but can get one during the night, that's an indication that it's not a physical problem. There's a test that a doctor will tell a man to do on himself if he's not getting erections, and is unsure if he's getting them during the night. He can wrap a thin strip of paper around the penis before bed, and if if it's torn in the morning that would indicate he had a nighttime erection.