-2

I have a problem to output a string. Can you help me?

In the following, const char * i and const char ** o are given.

The statement, "*o = temp" produces an error, saying that "std::string" and "const char *" do not fit. What is the problem?

int mytask(const char * i, const char ** o)
{
    std::string temp = std::string("mytask:") + i;

    *o = temp; //How to modify?

    return (0);
}
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
gnoejh
  • 325
  • 4
  • 16

4 Answers4

1

First of all you are trying to assign a local char pointer and use it in calling function, where it have already been destroyed. So instead you should do this. Assuming memory is allocated for o:

strcpy(*o,temp.c_str());
Nisarg
  • 11
  • 2
1

*o=temp means you are making the o point to a pointer that points to a std::string however o is a pointer that points to a char (or sequence of chars). This is not allowed. The other way around works: temp=*o because the std::string object defines what happens when you assign a char* to it (copy the null terminated string into the object). If you absolutely must copy from temp into the char* pointed to by o*. use strcpy() and std::string.c_str() strcpy(*o,temp.c_str())

vanjoe
  • 439
  • 4
  • 12
1

In C++, it's unusual to pass raw pointers around in this manner.

Returning 0 doesn't achieve much either.

I'd expect to see something like this:

std::string mytask(std::string const& i)
{
    return "mytask:" + i;
}

int main()
{
    std::string const number { '1' };
    std::string const ret { mytask(number) };
}
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
0

The statement strcpy(*o,temp.c_str()); didn't work. I resolved this problem by *o = temp.c_srt(); instead. Thanks all anyway.

gnoejh
  • 325
  • 4
  • 16