You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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*)的编译错误。

修复方案

  1. 修正数组类型:将main函数里的char* sports[]改为const char* sports[],明确字符串字面量的只读属性,符合标准要求。
  2. 修正函数参数:把processString的参数char* string改为const char* string——函数仅读取字符串内容,不需要修改,添加const既合规又能避免误操作。
  3. 修复逻辑笔误:代码中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:39:15