Search code examples
c++pointersconstantsdeclarationstring-literals

E0144 a value of type "const char *" cannot be used to initialize an entity of type "char *"


I'm trying to solve this issue E0144 a value of type "const char *" cannot be used to initialize an entity of type "char *"

It does compile on different compilers but it gives me errors on visual studio 2019 it doesn't compile

Errors C2440 'initializing': cannot convert from 'const char [9]' to 'char *' E0144 a value of type "const char *" cannot be used to initialize an entity of type "char *"

I tried solving the issue but can't seem to understand it.

#include<iostream>
#include<cstring>


using namespace std;

int processString(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 'p':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; // the number of vowels in string
}

int main() {

    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";
    }
}


Solution

  • The line

    char* sports[] = { "football","basketball","golf","cricket","Chess","badminton" };
    

    is valid in C, but not in C++. In C++, pointers to string literals must be of type const char *.

    Therefore, you should change the line to the following:

    const char* sports[] = { "football","basketball","golf","cricket","Chess","badminton" };
    

    If you want to pass a pointer to a string literal to the function processString, then you should also change the parameter of that function from char * to const char *.