allegro/c++ cannot convert argument 3 from 'const char *' to 'char *'

1.7k views Asked by At

I'm a noob trying to learn c++ and allegro and was following a tutorial which is how I came up with this code. My issue is at line:

"textout_centre_ex(screen, font1, Draw.c_str(), scrW / 2, scrH / 2, eBlue, -1);"

When it comes to 'Draw.c_str()' I get Error: argument of type "const char*" is incompatible with parameter of type "char*".

If I try and build I get "error C2664: 'void textout_centre_ex(BITMAP *,FONT *,char *,int,int,int,int)' : cannot convert argument 3 from 'const char *' to 'char *'"

How can I resolve this?

// Set variables
int counter = 0;
std::string Word = "SuperAwesomeTrivia";
std::string Draw = "";

FONT *font1 = load_font("font1.pcx", NULL, NULL);

while (!closeWindow){

// Update
    Draw += Word[counter];
    counter++;

    if (counter > Word.length() - 1)
    {
        closeWindow = true;
    }

    // Draw
    textout_centre_ex(screen, font1, Draw.c_str(), scrW / 2, scrH / 2, eBlue, -1);
    if (!closeWindow)
        rest(200);
    else
        rest(2000);
    clear_bitmap(screen);
}
destroy_font(font1);
allegro_exit();

return 0;
2

There are 2 answers

1
Ray On

(heads up: My C++ experience is a bit rusty, I might remember some C++ details inaccurately)

You are proving a function a different type of data than it is asking for. It It is asking for something mutable and you give it something immutable.

I think in practical terms, the function still receives a copy of the char pointer (thus it would not matter if it changed the value of the pointer internally), but the compiler is probably right to complain anyway.

To solve such a problem you could copy the entire text (char* points to an array of chars, terminated by \0, right?) to a new char array and provide that to the function. Maybe there is a newer version of the API that has changed the signature to incorporate the "const" for the parameter.

7
Emil Laine On

You can use const_cast to cast the argument to char* if the function is guaranteed to not mutate the pointed-to data:

textout_centre_ex(screen, font1, const_cast<char*>(Draw.c_str()), scrW / 2, scrH / 2, eBlue, -1);
                                 ^~~~~~~~~~~~~~~~~~            ~

A better solution would be to compile with GCC/Clang or #define AL_CONST const yourself before including any Allegro headers, so you get const in the places it should be in, and don't have to litter your code with ugly casts.