Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Passing std::string into Pointer-to-C-String Parameter [duplicate]

Tags:

c++

sdl

I'm using a function from SDL, and one of the parameters is of type const GLchar* const*, so in order to call it, I would need to pass in a reference of a C-string like this:

const char *str = "test";
glShaderSource(... , &str, ...);

However, I have an std::string that I want to pass in, and doing something like this gives an error:

std::string str = "test";
glShaderSource(... , &str.c_str(), ...);

I know that I can simply make a new const char* variable and save the std::string to it like this:

const char *cstr = str.c_str();

But is there any way around this? I don't like having to make a new variable. I tried using a lambda but that didn't work.

like image 374
Archie Gertsman Avatar asked Sep 02 '26 14:09

Archie Gertsman


1 Answers

No, there's no way around it.

The function glShaderSource needs a pointer to a pointer to a character buffer (because it wants you to pass one or more C-strings), and you can't take the address of an rvalue (which is what the expression str.c_str() is).

But that's not really a problem, since in your final example all you're doing is assigning a pointer to a pointer. This is extremely cheap and easy.

Don't be afraid of "making a new variable" — naming things is good anyway.

like image 168
Lightness Races in Orbit Avatar answered Sep 05 '26 03:09

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!