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

Time:12-10

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

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

int main(){
    int listsize = 4, charsize = 100;
    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[]
    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.

CodePudding user response:

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