0

I have a question regarding pointers/references, I couldn't find much information about, so, having this method declaration (C++):

void RequestParser::parseRequest(const char * request) 

When I want to use this method, I can call it like this:

requestParser.parseRequest(buffer);

So, going back to the definition the parameter expects a pointer (const char * request), why am I allowed to pass buffer without the reference, this way:

requestParser.parseRequest(&buffer);

This should be the correct way, right? Maybe there is some magic going on behind the scenes, like this:

void RequestParser::parseRequest(const char request[])

I know that you can't pass array as value (at least char arrays), so this is only syntactic sugar for this:

void RequestParser::parseRequest(const char * request) 

What am I misunderstanding?

redigaffi
  • 429
  • 6
  • 22
  • What's the type of `buffer`? – Mat Aug 19 '18 at 13:39
  • It's a char array, declared as: char buffer[2048] = {'\0'}; BTW why am I getting downvoted? – redigaffi Aug 19 '18 at 13:40
  • 2
    Possible duplicate of [What is array decaying?](https://stackoverflow.com/questions/1461432/what-is-array-decaying) – Alan Birtles Aug 19 '18 at 13:42
  • 1
    The ampersand, `&`, has several meanings. In types, it indicates a reference type; as a unary operator applied to one expression, it is the "address-of" operator and gives you a pointer (not a reference); as a binary operator it is "bitwise and". – molbdnilo Aug 19 '18 at 13:50

1 Answers1

3

When you pass an array like buffer to parseRequest, array-to-pointer decay occurs,

There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are:

So you're passing the pointer to the 1st element of the array in fact, it's of type char * (and could convert to const char*).

On the other hand, you can't pass &buffer, which is taking the address of the array and returns the pointer to the array (i.e. char (*)[2048]), it doesn't match the parameter type const char*.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405