Strange char * compilation error?

Is there something wrong with my code below? I got a compilation error!

typedef unsigned char BYTE;

void foo(char* & p)
{
 return;
}

int main()
{
  BYTE * buffer;
  // error C2664: 'foo' : cannot convert parameter 1 from 'char *' to 'char *&'
  foo ((char*)buffer);

  return 0;
}

Thanks in advance George

+3
source share
7 answers

Clicking BYTE*on it char*creates an unnamed temporary object with a type char*. The function being called takes a reference to char*, but you cannot reference such a temporary entity because it is not a real variable.

+14
source

You can perform reinterpret_cast<char*&>instead of static casting

foo (reinterpret_cast<char*&>(buffer));

Or you can make the argument a const reference:

void foo(char* const & p)
{
    return;
}
+7
source

foo . buffer - BYTE. , .

:

1) , , "&"; p. , .

2) , :

 BYTE * buffer;
 char * b = (char *) buffer;
 foo (b);
 buffer = (BYTE*) b;  // because foo may change b
+4

buffer - "lvalue", , :

(char*) buffer

"rvalue" ( " rvalue" - , ++ 0x). r.

const r. , :

void foo(char* const& p)  // added 'const'

. , lvalues, rvalues ​​ :

" rvalue", ++ 0x, , lvalues ​​ rvalues, ++ 98. , .

+2

, char *, .

, :

BYTE * buffer;
char* ptr = (char*)buffer;
foo(ptr); // now you have a matching variable to refer to. 

, .

+1

-,

(char)buffer

- - , char.

-, , , .

So yes, there are at least two things in your code.

+1
source

Write this:

int main() { 
  BYTE * buffer; 
  char* pbuf = (char*)buffer;
  foo(pbuf);
}
+1
source

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


All Articles