At the end of Ocarina of Time, the Hero of Time is returned to his childhood in order to seal the Door of Time. Because he experienced the future on the Adult Timeline as an adult, Link knows Ganondorf's plan to attack Castle Town and to gain entrance to the Sacred Realm via the Door of Time and obtain the Triforce. When Link returns to his childhood, the first place he is found is in Hyrule Castle Courtyard where he first met Zelda, who is spying on Ganondorf. The Hero of Time warns Zelda of Ganondorf's upcoming attack on Castle Town, so that they can prepare for his attack. Because the Hero of Time warned Zelda, Ganondorf's attack fails and he is captured. As shown on top of Arbiter's Grounds in TP, Ganondorf is put on trial and they attempt to execute him for treason.
Here's the tricky part. When they try to execute Ganondorf, he survives being stabbed and his hand glows, indicating that he has the Triforce of Power. It is theorized that Ganondorf obtained the Triforce on the CT because the Hero of Time returned with the Triforce of Courage (it is shown glowing on his hand in the courtyard scene), upsetting the balance of the Triforce that was held in the Sacred Realm on the CT. Take a look at this quotation:
Sheik said:
The Triforce...the sacred triangle...
it is a balance that weighs the
three forces:
Power, Wisdom and Courage.
If the heart of the one who holds
the sacred triangle has all three
forces in balance, that one will
gain the True Force to govern all.
But, if that one's heart is not in
balance, the Triforce will separate
into three parts:
Power, Wisdom and Courage.
Only one part will remain for the
one who touched the Triforce...the
part representing the force that
one most believes in.
If that one seeks the True Force,
that one must acquire the two
lost parts.
Those two parts will be held
within others chosen by destiny,
who will bear the Triforce mark
on the backs of their hands.
By returning with the Triforce of Courage when the Triforce was whole, it is likely that the Triforce had to balance itself by redistributing itself into its three fragments as Sheik described, similar to how it distributed itself on the AT when Ganondorf obtained the Triforce of Power. In order to maintain the balance, Ganondorf must have been given the Triforce of Power on the CT when the Hero of Time returned, and Ganondorf's fragment must have activated when he was in danger of being killed on top of Arbiter's Grounds.