Search code examples
c++stringstructchar-pointer

Passing multiple string to a function from c++ code to c code throw an error


I have a struct as below

struct st
{
        std::string name;
        std ::string refer;
        int number;
        std::string path;
};

Have created array of above structure as

struct st var[5]={{"rick1","ross1",1,"demo1"},
                { "rick2","roos2",2,"demo2" },
                { "rick3","roos3",3,"demo3"},
                {"rick4","roos4,4,"demo4"},
                {"rick5","roos5",5,"demo5"}};

Now i called my userdefine function (pass) as

c++ code

for(i=0;i<5;i++)
pass(var[i].name.c_str());// how can i pass  name sting to char *?

c code

void pass(char *name) //  implemented in c code so cannot use string
{
cout<<name<<endl;

}

I m supposed to pass name which is string type in calling function(c++ code) to called function(c code) which is char * type .I m using c_str() but it throw an error .Please help me out thanks in advance

Note: pass function is called from c++ code which pass string as an argument to c code which catch as char *


Solution

  • name.c_str() returns a const char*. You can't pass a const pointer as an argument for a function taking a non-const pointer.

    If you have a very recent compiler, you may be able to use std::string::data() which has a non-const overload since the C++17 standard.

    Otherwise you would need a const_cast:

    pass(const_cast<char*>(var[i].name.c_str()))
    

    I'm assuming here that the pass function does not actually modify the string.