Can a name be copyrighted? No!
However, a unique name used in your book is covered by copyright along with your works. But it does not afford you any protection until such time the name has a "secondary meaning."
In other words, when the characters name becomes recognized as belonging to your work as a "source identifier."
Once you meet the above two requirements, then you could apply for a "trademark" of your characters name.
I did not check on the name 'Gandalf' you mentioned. But there are other laws that may or may not let you use that name. As an assumption, let's say the name 'Gandalf' is not trademarked, and is not restricted by the books copyright notice (more on this in a moment).
The copyright holder of the work where 'Gandalf' was first used, could come after you using any one of several laws. One of these is 'anti-dilution,' another is 'passing-off.'
One of the protection clauses my publisher added to all my works contains the following line. "All fictional product names, business names, or location names, that appear in this publication are the property of the author and may not be used as names, bylines or slogans for real products, businesses, locations or services without the prior written permission of the author."
This same clause also allows me to retain all rights, so if an item, doll, character, toy, hat, beer mug, company, you name it, I can place said name under contract. More money is often made from the sale of goods, products, or services, based on a line or name found in a book.
In other words, cover your bases as best as allowed by law.
As an aside: The name 'Gandalf' comes from Norse Mythology, which means it is public domain. However, the Character 'Gandalf' as used in "Lord of the Rings" is Trademarked, as are the dolls, film character, etc.
As long as YOUR character 'Gandalf' in no way resembles Tolkien's character, you may have a leg to stand on. The question is, do you want to risk it?
I am not an attorney and this is not to be construed as legal advice.
Merely as commentary from a fellow author.