When you buy a stock, where does the money go?

The first time a company sells stock, it is called and Initial Public Offering (IPO). When you purchase stock during the IPO, the money goes to the company whose stock you are buying.

The second time the same company wants to sell stock (raise money from the public), it is called as a Follow on Public Offer (FPO). When you buy stock during FPO, the money again goes to the company whose stock you are buying.

These two fall under "Primary Market".

Once you buy the stock, you can sell it again in the "Secondary Market".

So when people trade on NSE, BSE, NYSE, etc. it is trading in the secondary market.
Secondary Markets are nothing but market places where the buyer meets the seller. When you sell the stock in these markets, the money comes to you and the stock gets transferred to the buyer. Now you can repurchase stock of the same company from other sellers who either bought stock from the company (during the IPO/FPO) or from other sellers (like the one to whom you sold the stock earlier). This transaction will be between you and the seller, so like any other transaction, you pay money to the seller and he gives you the stock.

The Stock Exchanges in the world are just companies that build a Market Place where the seller and the buyer meet and transact. They earn a small commission for each transaction.