为何无法将char*转换为char?C++两种赋值方式差异解析
char *s="hello"; Works But char *s; *s="hello"; Throws an Error Let's break this down clearly—this is a classic pointer misunderstanding that trips up a lot of new C++ developers!
First, Let's Look at char *s="hello";
When you write this line, you're combining two valid operations into one:
- Declaring a pointer variable
sof typechar*(a pointer that points to achar). - Initializing that pointer to point directly to the starting memory address of the string literal
"hello".
Under the hood, "hello" is stored in memory as a null-terminated char array (it looks like {'h','e','l','l','o','\0'}). The string literal itself evaluates to the address of its first element ('h'), so assigning that address to s makes perfect sense—s now points to the start of the string.
Side note: In modern C++, you should use
const char* s = "hello";instead. String literals are read-only, and writing to them leads to undefined behavior. This isn't the cause of your error, but it's a good practice to follow.
Now, Why char *s; *s="hello"; Fails
This code has two critical issues, and the type mismatch is the direct reason for your compiler error:
- Uninitialized wild pointer: When you declare
char *s;without initializing it,sis a "wild pointer"—it points to some random, unpredictable spot in memory. Accessing this memory is already risky (it could crash your program or cause weird behavior). - Type mismatch: The error
cannot convert char* to charcomes from the line*s="hello";. The*ssyntax is called dereferencing the pointer—it means "access the singlecharvalue thatsis pointing to". So*sis a singlecharvariable, not a pointer. But"hello"evaluates to aconst char*(a pointer to achararray). You can't assign a pointer value to a singlechar—they're completely incompatible types!
If you wanted to assign the string to s after declaring it, the correct code would be:
char *s; s = "hello"; // Assign the address of the string literal to the pointer s
Again, use const char* here to avoid undefined behavior if you accidentally try to modify the string.
Key Takeaways
char *s="hello";initializes the pointersto point to the start of the string literal.char *s; *s="hello";tries to assign a pointer (the string's address) to a singlechar(the value at the pointer's random location)—this type mismatch is why the compiler throws an error.- Always initialize your pointers! Wild pointers are a common source of hard-to-debug bugs.
内容的提问来源于stack exchange,提问作者vishal rana

