0

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 *

leuage
  • 566
  • 3
  • 17
  • 1
    Please read [this `c_str` reference](http://en.cppreference.com/w/cpp/string/basic_string/c_str). Pay attention to what type it returns. – Some programmer dude Feb 19 '17 at 12:03
  • 1
    If it's *your user-defined* function, define it right, that is with `std::string&` parameter. Note that in the \*new\* c++11, you have `std::string::data`. – LogicStuff Feb 19 '17 at 12:03
  • @Biffen OP would then use `char const*` and there wouldn't be a question. – LogicStuff Feb 19 '17 at 12:06
  • I'm just confused by *"this not the valid chose since char * will keep on changing in my case"*. Does OP want to modify it? – LogicStuff Feb 19 '17 at 12:09
  • @LogicStuff thanks for the response. i can't change function definition since it is c code and m calling from c++ code – leuage Feb 19 '17 at 12:19

1 Answers1

1

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.

zett42
  • 25,437
  • 3
  • 35
  • 72