The axons of each nociceptor neurone* (pain-sensing neurone) travel until they reach the dorsal horn of the spinal cord, where they synapse with a secondary neurone. In fact, each primary nociceptor neurone synapses with multiple secondary neurones, and each secondary neurone receives multiple inputs.
One odd thing about this system is that the nociceptor neurones innervating the visceral organs (like the heart, diaphragm or gallbladder) always terminate in a secondary neurone that they share with nociceptor neurones innervating a patch of skin. This is illustrated schematically in the following diagram:
The problem with this arrangement is that the secondary neurone, and thus the brain, will therefore have no way of telling whether it was activated by trouble in the skin or by trouble in the visceral organ. All it knows is that it has been activated, but it can't say from which of the two sources this signal came.
So what does the brain do? As it turns out, it resolves this dilemma by choosing to represent this pain as coming from the skin. Perhaps it takes this option because the skin is much more likely to actually be the source. (However, I'm pretty sure an electrician could do better than this odd system!)
Therefore, if a visceral organ is damaged or inflamed, we will feel this pain as if it comes from a particular part of our skin. Exactly where on the skin we feel it depends on which of the secondary neurones they share. For instance, the innervation of the diaphragm comes from the cervical spinal neurones in the C3-5 area. The part of the skin that these nerves also innervate is situated around the shoulder. Thus, if the diaphragm is inflamed, the patient will complain of pain around the shoulder! Similarly, pain in the heart (e.g. during an angina attack) is referred to the centre-left chest, left shoulder and/or left arm (and sometimes even the left jaw). And so on.
* 'Neurone' is the usual spelling of the word, but Americans and Candadians spell the word 'neuron' instead. Take your pick - I don't care!