I have the following code:
glShaderSource(shader, 1, (const char **)data.c_str(), NULL);
But it makes my program crash. How do I convert
The return value of std::string::c_str()
is a pointer value (i.e., an address) to a static string array held inside the data-structures of the std::string
object. Since the return value is just a temporary r-value (i.e., it's just a number stored in a CPU register), it is not an l-value and therefore it does not have a memory address you can actually take the address of and cast to a pointer-to-pointer. You first must save the return pointer value in a memory address. Memory-locations are l-values, and can have the address-of operator applied to them. So that is why your second method (or Dark Falcon's method) works, although keep in mind that the pointer value returned is a temporary, meaning that if you do any operations on the std::string
object, it could invalidate the pointer since the std::string
object internally manages the memory of its data-structures. So just because you've saved the return pointer value in a memory location doesn't mean that the pointer won't be invalidated at some later time, and at a point that you may not be capable of deterministically choosing.