编译C++代码遇类型不兼容错误:char与const char*赋值问题求助
Hey there! Let's break down why you're hitting this error and get your custom strcpy working smoothly.
What's Causing This Error?
This error boils down to a type mismatch: you’re trying to assign a string pointer (const char*) directly to a single character (char). When building your own strcpy, this almost always happens because you forgot to dereference the source pointer to grab the actual character it points to.
Here’s a common incorrect implementation that triggers this exact error:
void my_strcpy(char* dest, const char* src) { while (*src != '\0') { *dest = src; // ❌ Error! src is a const char*, *dest is a char dest++; src++; } *dest = '\0'; }
In the marked line, src is a pointer pointing to the current character in the source string. You don’t want to assign the pointer itself—you need the character it’s pointing to.
Correct Custom strcpy Implementations
Let’s fix this with two practical approaches:
1. Readable Explicit Loop Version
void my_strcpy(char* dest, const char* src) { // Add null pointer checks to avoid crashes if (dest == nullptr || src == nullptr) { return; } // Copy each character until we hit the null terminator while (*src != '\0') { *dest = *src; // ✅ Dereference both pointers to access characters dest++; src++; } // Don't forget to append the null terminator to the destination *dest = '\0'; }
2. Concise Idiomatic Version (Matches Standard Library Behavior)
The standard strcpy returns the original destination pointer, enabling chained calls. Here’s a compact implementation that follows this convention:
char* my_strcpy(char* dest, const char* src) { if (dest == nullptr || src == nullptr) { return dest; } char* original_dest = dest; // Save the starting address to return later // This line handles 3 tasks at once: // 1. Copies *src to *dest // 2. Increments both pointers // 3. Checks if the copied character is '\0' to exit the loop while ((*dest++ = *src++) != '\0'); return original_dest; }
Key Takeaways
- Always dereference your pointers (
*src,*dest) when working with individual characters—never assign the pointer itself to acharvariable. - Never skip adding the
'\0'null terminator to the destination string; without it, the result won’t be a valid C-style string. - Adding null pointer checks makes your function more robust and prevents unexpected crashes.
- Following the standard library’s return convention (returning the original destination pointer) makes your implementation compatible with existing code patterns.
内容的提问来源于stack exchange,提问作者DreadedSlug

