Search code examples
c++referenceconstantsreference-binding

invalid initialization of non-const reference of type 'const char*&' from an rvalue of type 'const char *'


i made a mystrcpy function,

void mystrcpy(char *&stuff, const char *&otherstuff){
    for(int i=0; stuff[i]&&other[i]; i++){
        stuff[i]=other[i];
    }
}

and a main function:

int main(){
    char *hello="hello";
    mystrcpy(hello, "bye bye"/*<--i have no clue what data type this really is!!*/);
    printf("%s\n", hello);
    return 0;
}

it does not compile, and says "invalid initialization of non-const reference of type 'const char*&' from an rvalue of type 'const char *'"...

when i just do:

const char *bye="bye bye";
mystrcpy(hello, bye);

it compiles without error.

i need to know why the former one doesnt work, thanks.


Solution

  • Your function takes a reference to a pointer, which is a bit unusual. Notably, this means that the input must be a pointer that has its own storage (so that you can take a reference to the pointer).

    const char *bye="bye bye"; mystrcpy(hello, bye); works because bye is a pointer variable, so you can take a reference to it.

    mystrcpy(hello, "bye bye") fails because "bye bye" is not a pointer - it's an array of characters (a const char [8]) and so there's no pointer to take a reference to.

    You do not need the reference & in your mystrcpy function signature - that simply makes the function harder to use, and can introduce interesting bugs if you accidentally adjust the pointers in the function (e.g. if you started doing *stuff++ = *other++;).