Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to pass char** as a const char*[] to a function?

I have a char** variable and I want to pass it to a function that accepts const char*[]

int getList(const char* list[], int count){

}

int main(){
    int listsize = 4, charsize = 100, res = 0;
    char** li = nullptr;

    li = new char*[listsize];
    for (int i = 0; i<listsize; i++){
        li[i] = new char[charsize];
        strcpy(li[i],"Please Help ME!");
    }
    
    //This is where I get the compiler error because char** is not const char* list[]
    res = getList(li,listsize);

    for (int i = 0; i<listsize; i++) delete[] li[i];
    delete[] li;
} 

I tried to cast it but couldn’t get it to work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const can only be added to the "innermost" member of a set of multiple pointers, so a char ** cannot be automatically converted to a const char **. You’ll need to add a const_cast:

res = getList(const_cast<const char **>(li),listsize);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading