user2333234
user2333234

Reputation: 553

invalid conversion from 'const char*' to 'char*'

Have a code as shown below. I have problem passing the arguments.

stringstream data;
char *addr=NULL;
strcpy(addr,retstring().c_str());

retstring() is a function that returns a string.

//more code
printfunc(num,addr,data.str().c_str());

I get the error

invalid conversion from 'const char*' to 'char*'.

initializing argument 3 of 'void Printfunc(int, char*, char*)'on argument 3 of the function

on the above line. The function is called as shown below

void Printfunc(int a, char *loc, char *stream)

please let me know if I need to change any initialization.

Upvotes: 51

Views: 212112

Answers (4)

VainM
VainM

Reputation: 21

c_str() will give you a const char *

For converting const char * to char * you can use strdup like this.

char * success = strdup(data.str().c_str());

also it will make a new malloc so it creates a duplicate.

so you need to do this

char * success = strdup(data.str().c_str());
printfunc(num, addr, success);
free(success);

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

First of all this code snippet

char *addr=NULL;
strcpy(addr,retstring().c_str());

is invalid because you did not allocate memory where you are going to copy retstring().c_str().

As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.

Upvotes: 3

Louis93
Louis93

Reputation: 3913

string::c.str() returns a string of type const char * as seen here

A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str());

While the above may work, it is undefined behaviour, and unsafe.

Here's a nicer solution using templates:

char * my_argument = const_cast<char*> ( ...c_str() );

Upvotes: 22

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

Well, data.str().c_str() yields a char const* but your function Printfunc() wants to have char*s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be

void Printfunc(int a, char const* loc, char const* stream)

The alternative might be to turn the char const* into a char* but fixing the declaration is preferable:

Printfunc(num, addr, const_cast<char*>(data.str().c_str()));

Upvotes: 65

Related Questions