invalid conversion from `const char*' to `char'

This is a discussion on invalid conversion from `const char*' to `char' within the C++ Programming forums, part of the General Programming Boards category; I'm having a problem with using character variables. I'm trying to make a char variable equal a string like "hello" ...

you are declaring an array of characters. Generally, you cannot assign a string literal like "hello" to an array of characters. However, there is one little twist: with character arrays, you are able to assign a string literal to them at the time you declare them. For instance, you can do this:

char arp[20] = "hello";

When you do that the compiler will copy "hello" into the arp array character by character, and fill the remaining index positions with '\0' characters. You cannot subsequently do this, though:

arp = "bye";

because that doesn't fit the requirements: you are not assigning the string literal to arp at the time you declare arp. arp has already been declared.

That is if you still want to use this. In this way, only the memory addresses of "ehllo" or "bye" are assigned to the arp* pointer, and it all works. However, std::string is overpoweringly great, so whatev. I don't know the exact reason why you can't assign things like you did, I can't really think of how it would look on a low level...

This is pointer assignment, and this is why you could not get it to work correctly. When you declare an array statically, it has a fixed position, and your named variable will always point to that location until it the array goes out of scope, and gets reclaimed by the system. What the above code tries to do is assign 'arp' to point to the string literal "hello" which is probably somewhere in read-only memory, but since you cannot reassign this pointer, you get an error.

That is if you still want to use this. In this way, only the memory addresses of "ehllo" or "bye" are assigned to the arp* pointer, and it all works. However, std::string is overpoweringly great, so whatev. I don't know the exact reason why you can't assign things like you did, I can't really think of how it would look on a low level...

No, no, no, no. That's bad. You've just created a memory leak by reassinging the address stored in the pointer from the memory you allocated initially using the new operator to a different address (the address of one of the string literals). Bad things could happen if you were to attempt to call delete on the pointer. If you don't belive me run this:

"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens