0

As in the code below, I can't pass this parameter, how do I fix it?

E0167 The "const char *" type argument is incompatible with the "char *" type parameter

Code example:

#include <iostream>
using namespace std;

int PrintString(char* s)
{
    cout << s << endl;
}

int main(int argc, char* argv[])
{
    PrintString("TESTEEEE");
    return 0;
}

I've already tried PrintString(L"TESTEEEE");

I've also tried setting the Project -> Properties -> General -> Character Set option to use Multi-Byte Character Set.

error image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
FoioLag
  • 59
  • 8
  • 2
    As it says, "TESTSEEE" is a const char *. Change `int PrintString(char* s)` to `int PrintString(const char* s)`. – Mikael H Jun 18 '20 at 21:28
  • ***I've already tried PrintString(L"TESTEEEE");*** For wide character literals you want `int PrintString(const wchar_t* s)` – drescherjm Jun 18 '20 at 21:30
  • Either change the function proto, or const_cast the argument to char *. Remember that modifying literals is UB. – bipll Jun 18 '20 at 21:31
  • why can't you edit the function to make its first parameter `const wchar_t* s`? – Alberto Sinigaglia Jun 18 '20 at 21:36
  • Does this answer your question? [Difference between char\* and const char\*?](https://stackoverflow.com/questions/9834067/difference-between-char-and-const-char) – alter_igel Jun 18 '20 at 21:36

2 Answers2

4

This literal "TESTEEEE" is of type char const[9]. When used as an argument to a function, it can decay to char const* but not to char*. Hence to use your function, you have to make the parameter fit to your argument or the opposite as follows

#include <iostream>

using namespace std;
int PrintString(const char* s)
{
    cout << s << endl;
}


int main(int argc, char* argv[])
{

    PrintString("TESTEEEE");

    return 0;
}

live

OR

#include <iostream>

using namespace std;
int PrintString( char* s)
{
    cout << s << endl;
}


int main(int argc, char* argv[])
{
    char myArr[] = "TESTEEEE";
    PrintString(myArr);

    return 0;
}

live

R Sahu
  • 204,454
  • 14
  • 159
  • 270
asmmo
  • 6,922
  • 1
  • 11
  • 25
2

You have incorrect constness, it should be:

void PrintString(const char* s)
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 3
    Supplemental background information: [String Literal](https://en.cppreference.com/w/cpp/language/string_literal) A literal isn't necessarily stored in writable memory, so to prevent accidentally writing to one, they are marked `const`. – user4581301 Jun 18 '20 at 21:33