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


i made mystrcpy function,

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

and main function:

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

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

when do:

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

it compiles without error.

i need know why former 1 doesnt work, thanks.

your function takes a reference pointer, bit unusual. notably, means input must pointer has own storage (so can take reference pointer).

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

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

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


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - How to Hide Date Menu from Datepicker in yii2 -