Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialization of non-const reference of type 'char*&' from a temporary of type 'char*'

Tags:

c++

reference

void test3(char * &p){
    strcpy( p, "aaaaaaaaaaaaaaaaaaaaaaaaaa");
}


char c[] = "123";
test3(c);

the code above is compiled failed:

initialization of non-const reference of type 'char*&' from a temporary of type 'char*'

why char c[] can't be referenced by the argument p?

like image 541
makicn Avatar asked Feb 16 '23 12:02

makicn


1 Answers

Because the type of c is char[4], i.e. an aray of four chars. Your reference needs a char*, i.e. a pointer to char.

Arrays are not pointers. In most cases, they decay to a pointer to first element when used, but that decay-produced pointer is temporary. As such, it cannot bind to a non-const reference.

Why is your function taking a reference in the first place? It would be perfectly fine taking char*.

like image 176
Angew is no longer proud of SO Avatar answered Apr 12 '23 23:04

Angew is no longer proud of SO