0

I'm making a game in opengl and I've had an issue with converting a string to a const char*. Here is my code:

    for (GLuint i = 0; i < faces.size(); i++)
    {
        string      fileName(faces[i]),
                    texture = "../content/skybox/" + fileName + ".jpg";
                    faces[i] = texture.c_str();
    }

Unfortunately once run, the faces[i] just becomes a mess.

Chris Ross
  • 41
  • 6

2 Answers2

1

You have undefined behaviour:

Texture AssetController::LoadCubeMapTexture(vector<const GLchar*> faces, string ID)
{
    for (GLuint i = 0; i < faces.size(); i++)
    {
        string      fileName(faces[i]),
                    texture = "../content/skybox/" + fileName + ".jpg";

                    // !!!! texture is a local variable and will be
                    //      destroyed once its scope ends (which is 
                    //      on next for iteration, or when for ends).
                    faces[i] = texture.c_str();
    }

the solution is to change interface to return vector of filenames:

Texture AssetController::LoadCubeMapTexture(vector<const GLchar*> faces, string ID, 
                               std::vector<std::string>& facesFileNames)
{
    for (GLuint i = 0; i < faces.size(); i++)
    {
        string      fileName(faces[i]);
        std::string texture = "../content/skybox/" + fileName + ".jpg";
        facesFileNames.emplace_back(texture);
    }
marcinj
  • 48,511
  • 9
  • 79
  • 100
0

As soon as you leave the loop your std::string texture goes out of scope, it's destructor gets called and the memory pointed to by faces[i] becomes invalid.

Just use std::vector<std::string> instead.

On a site note: Don't do using namespace std.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43