Search code examples
c++pointersdouble-pointer

Why in C++ do I need to pass a pointer by reference to change the pointed content?


I am writing a function to load text from shader code file. I have stumbled upon something strange regarding pointers and I cannot figure out why.

I have a function named Load. In this function I copy text, taken from a file stream, in the output variable.

static void Load(const GLchar* source_path,  GLchar* output,GLint& count )
{
    string code;

    // loading logic here
    code= vShaderStream.str(); // copying the string from the stream
    count = code.length(); 
    output = new GLchar[count];
    std::size_t length = code.copy(output, count, 0);
    output[length]= '\0';
}

Load is called in this way:

for (size_t i = 0; i < d_n_fragment; i++)
{
    Load(d_fragment_source_path, d_fragment_code[i], d_fragment_string_count[i]);
} 

where d_fragment_code is a double pointer of Glchar** which is already initialized. After Load function is called the pointer d_fragment_code[i] contains no text. I tried to change the signature of the Load function to:

static void Load(const GLchar* source_path,  GLchar*& output,GLint& count )

and thus passing the pointer by reference. It works, after the function is called d_fragment_code holds correctly the text loaded from the file but I don't understand why a pointer it is to be passed by reference.

I thought that passing a pointer only would suffice to change its content. I am confused, could you shed some light on it?


Solution

  • You should pass pointers by reference if you have to modify the pointer rather than the object that the pointer is pointing to.

    Using double pointers is also a similar case.

    Here is a more detailed article:
    http://www.codeproject.com/Articles/4894/Pointer-to-Pointer-and-Reference-to-Pointer