VS2019编译报错E0144/C2440:const char*无法初始化char*实体
解决Visual Studio 2019中E0144/C2440编译错误
问题根源
C标准明确规定,字符串字面量(比如"football")属于**const char[]类型**,内存空间是只读的。直接将其赋值给char*变量,会允许代码后续修改这片只读内存,触发未定义行为。部分编译器(如GCC默认配置)会放宽此限制,但Visual Studio 2019严格遵循C标准,因此抛出E0144(const char无法初始化char实体)和C2440(无法将const char[]转换为char*)的编译错误。
修复方案
- 修正数组类型:将
main函数里的char* sports[]改为const char* sports[],明确字符串字面量的只读属性,符合标准要求。 - 修正函数参数:把
processString的参数char* string改为const char* string——函数仅读取字符串内容,不需要修改,添加const既合规又能避免误操作。 - 修复逻辑笔误:代码中switch分支的
case 'p':case 'U':是错误输入,应改为case 'u':case 'U':,否则无法正确统计元音字母u。
修复后的完整代码
#include<iostream> #include<cstring> using namespace std; int processString(const char* string) { int vowels = 0; bool a = false, e = false, i = false, o = false, u = false; for (int k = 0; k < strlen(string); k++) { switch (string[k]) { case 'a':case 'A': a = true; break; case 'e':case 'E': e = true; break; case 'i':case 'I': i = true; break; case 'o':case 'O': o = true; break; case 'u':case 'U': u = true; break; // 修正笔误 } } vowels += a ? 1 : 0; vowels += e ? 1 : 0; vowels += i ? 1 : 0; vowels += o ? 1 : 0; vowels += u ? 1 : 0; return vowels; } int main() { const char* sports[] = { "football","basketball","golf","cricket","Chess","badminton" }; int vowels; for (int j = 0; j < 6; j++) { vowels = processString(sports[j]); cout << "String '" << sports[j] << "' contains '" << vowels << "' vowels.\n"; } return 0; }
补充说明
如果确实需要修改字符串内容,不能直接用字符串字面量赋值,需要先将其复制到可修改的char数组中,示例:
char football[] = "football"; // 此时数组内存可修改
内容的提问来源于stack exchange,提问作者mariio
相关产品推荐
相关产品推荐

