I have the following code:
glShaderSource(shader, 1, (const char **)data.c_str(), NULL);
But it makes my program crash. How do I convert std::string
into const char **
? I also tried (const char **)&
but it said "requires l-value" which I don't understand. It works fine when I use this code:
const char *data = "some code"; glShaderSource(shader, 1, &data, NULL);
But I can't make it work directly from a std::string
. I could allocate a new char
array for it but that is not nice code.
I also tried with const GLchar
but obviously it makes no difference.
This can be done with the help of c_str() and strcpy() function of library cstring. The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string.
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'). It returns a null pointer to the string.
Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.
data.c_str()
returns a const char*
, so do this:
const char *c_str = data.c_str(); glShaderSource(shader, 1, &c_str, NULL);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With