How does training work?
So let's say I take a gym, and I place a CP 100 Charmander to hold it. Then, I do a friendly battle, picking my Pinsir to battle against Charmander. What happens if I win/lose? Is the XP that I gain used to level up my Charmander or increase its CP level? I got an achievement for training 10 Pokémon, but their CP levels are still the same. I don't get how it works.
Solution 1:
When you battle against a gym that belongs to your team (training), if you win, you get an XP bonus for yourself, and a Prestige (reputation) bonus for the gym. Enough of the latter and the gym levels up. Higher level gyms can hold more Pokémon (one per trainer), which makes it harder for opposing teams to take over the gym. If you lose against your gym, no bonus for either you or the gym. The Pokémon you initially put in the gym stays there until it's bumped out by the gym losing enough Prestige to drop one or more levels (the lowest CP Pokémon drop off the lower end of the ladder, essentially). The gym loses Prestige by having opposing teams win against it.
If your gym Pokemon is returned to you as a result of the gym losing enough Prestige, your returned Pokemon is returned fainted, with no health, requiring healing via a Revive and Potions before another battle.
In your example, I don't think either of your Pokémon (Charmander left at gym to train, or the Pinsir you bring in to challenge) gain anything (it'd make sense if they did, but I haven't seen it).
Solution 2:
Carl's answer covers the basics but misses some details.
You don't have to win a battle to affect prestige. As long as you defeat at least one defending Pokémon, you'll have an impact on the gym's prestige. This makes it easier to impact a gym with low-levelled Pokémon. You'll have a bigger impact the more opponents you defeat. I don't know if this is modified based on your/your Pokémon's levels.
When training at a friendly gym, you battle all defending Pokémon with a single attacker, and your prestige modifications are added to the gym. When attacking an opposing gym, you battle all defending Pokémon with a squad of six, and your prestige modifications are deducted from the gym.
When the gym levels up due to prestige, an extra defender slot becomes available for other players of the reigning team. When a gym levels down, defenders will be removed if there isn't a slot for them, starting with the lowest CP defender.
When a gym is reduced to 0 prestige, it becomes available to claim. Newly claimed gyms start at level 2 (with 2000 prestige), with room for 2 defenders. Placing defenders will raise the prestige. I don't know if this depends on the player level or Pokémon CP, but I think it's a flat 2000. As such, 3 defenders can go down and leave the gym at 6000 prestige.