Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ISO C++11 does not allow conversion from string to char

Tags:

c++

From what I read here, you can't do :

char *delegates[]={"IN",NULL};

it has to be this so you do not get a warning :

const char *delegates[]={"IN",NULL};

But I have some function that I can't change that looks like :

void Interpreter::setBuiltIns(char *builtins[],int num  )

This function is not going to change the array in any way.

If I try to pass it the strings array with :

myclass.setBuiltIns(delegates, 1);

I get an error, but if I remove the const from delegate there is no error but I get the ISO warning .

How can I keep this function, and pass it the array without a warning/error.

like image 432
Curnelious Avatar asked Apr 15 '17 19:04

Curnelious


People also ask

How do I convert a string to a number in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.

What is a char * in C++?

char* is typically used to iterate through a character array, i.e., a C string. It is rarely used as a pointer to a single char, unlike how other pointers are typically used. C++ has newer constructs for strings that typically should be used.

Can you convert a string to a char in C?

The c_str() and strcpy() function in C++C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').


1 Answers

Depends. If it is guaranteed that setBuiltIns does not modify the strings, you can just const_cast the const away.

Otherwise, choose the always safe path and copy the literals into new buffers.


As requested, an example for the first variant:

void fun(char *builtins[]){}

int main () {
    const char *delegates[] = {"IN",nullptr};
    fun(const_cast<char **>(delegates));
}
like image 152
Baum mit Augen Avatar answered Sep 17 '22 19:09

Baum mit Augen