No matter in which way you point the north pole of a freely suspended magnet, it will always come to rest in the geographical north-south direction. This means thare there must be an invisible magnet inside the earth- which is partly true- the earth's magnetic field is also around the earth.
How is the magnetic field generated? Well, our earth's magnetic field is said to be generated deep inside the earth's core. Right at the heart of the Earth is a solid inner core, two thirds of the size of the Moon and composed primarily of iron. At a hellish 5,700C, this iron is as hot as the Suns surface, but the crushing pressure caused by gravity prevents it from becoming liquid.Surrounding this is the outer core, a 2,000 km thick layer of iron, nickel, and small quantities of other metals. Lower pressure than the inner core means the iron here is fluid. Differences in temperature, pressure and composition within the outer core cause convection currents in the molten metal as cool, dense matter sinks while warm, less dense matter rises. The Earths rotation also causes swirling whirlpools in the core. This flow of liquid iron generates electric currents, which in turn produce magnetic fields. Charged metals passing through these fields go on to create electric currents of their own, and so the cycle continues. This self-sustaining loop is known as the geodynamo. These two seperate magnetic fields conjoin to form a vast magnetic field.
The magnetic north pole faces the geographical south pole, and the magnetic south pole faces the geographical north pole. Since opposite poles attract each other and like poles repel each other, the north pole of the freely suspended magnet points towards the magnetic south pole, thus pointing towards the geographical north pole of the earth.
The magnetic compass works in a similar way. Think of it as a freely suspended magnet- pointing towards the north pole- but actually towards the magnetic south pole!