A.Agan
A.Agan

Reputation: 105

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){ return 0;}

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.

Upvotes: 0

Views: 173

Answers (1)

dbush
dbush

Reputation: 223719

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);

Upvotes: 3

Related Questions