Initializing a non-constant reference of type 'char * &' from the temporary type 'char *'

void test3(char * &p){ strcpy( p, "aaaaaaaaaaaaaaaaaaaaaaaaaa"); } char c[] = "123"; test3(c); 

compiled code compiled:

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

why can't char c[] refer to p argument?

+4
source share
3 answers

Since type c is equal to char[4] , that is, aray of four char s. Your link requires char* , that is, a pointer to char .

Arrays are not pointers. In most cases, they break up into a pointer to the first element when using it, but this shortened pointer is temporary. Thus, it cannot communicate with a non-constant link.

Why is your function accepting the link in the first place? It would be great if you take char* .

+7
source

You can change your code by taking an intermediate variable as:

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

And since you are trying to copy a relatively long string than length, you can damage the variable.

0
source

You can change your code by adding the modifier "const" so that you do not change the address c:

 void test3(char * const &p){ strcpy( p, "aaaaaaaaaaaaaaaaaaaaaaaaaa"); } char c[] = "123"; test3(c); 
0
source

Source: https://habr.com/ru/post/1498319/


All Articles