Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a char pointer to a function accepting a reference to a char array

Tags:

c++

I'm trying to call this method

#define SIZE 16
void DoSomething(char(&value)[SIZE])
{
}

From this method:

void BeforeDoingSomething(char* value, int len)
{
    if (len == SIZE)
    {
        DoSomething(value);
    }
}

Attempting to do this gives me this error:

a reference of type "char (&)[16]" (not const-qualified) cannot be initialized with a value of type "char *"

Any tips for how to get the compiler to accept value passed in the function BeforeDoingSomething?

like image 861
Zulukas Avatar asked Sep 28 '18 17:09

Zulukas


2 Answers

As the error explains, you cannot initialize a reference to an array using a pointer.

If and only if you can prove that value does in fact point to (first element of) an array of appropriate type, then what you can do is explicitly reinterpret the pointer, and indirect it:

DoSomething(*std::launder(reinterpret_cast<char(*)[SIZE]>(value)));
like image 98
eerorika Avatar answered Oct 16 '22 17:10

eerorika


You can do it like this, but only in the case if there is a char[16] at the address where value points:

DoSomething(*std::launder(reinterpret_cast<char (*)[16]>(value)));

It is the same case as the first example here.

like image 3
geza Avatar answered Oct 16 '22 18:10

geza