2

I have a static array of integers that I never want to change. I have a C-style function that wants to have this array as a void-pointer parameter. I am trying out different combinations of const_cast and reinterpret_cast, but I'm coming to the point where I have no clue of what I'm exactly doing and it keeps giving me errors.

class Foo
{
    static constexpr int bar[3] = {1,2,3};

    void method()
    {
        cfunction(reinterpret_cast<void*>(const_cast<int*>(&bar)));
    }
};

invalid const_cast from type 'const int ()[3]' to type 'int'

I see that it fails because the types don't match. I also tried const_cast<int[]>(bar), but const_cast wants to have a pointer or reference type.

Where can I read up on this subject? It's hard for me to understand what is going on here.

Marnix
  • 6,384
  • 4
  • 43
  • 78

3 Answers3

4
cfunction((void*)bar); 

P.S. I 've seen lots of programmers struggling to use all these casts when, in reality, they only need the simple C cast. If you insist on the C++ cast style, then

cfunction(reinterpret_cast<void*>(const_cast<int*>(bar)));

(Remove the & from bar).

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
3

As the compiler says, &bar is a const int (*)[3] - a pointer to an array - and you can't const_cast that to an int*.

You want a pointer to the array's first element, not to the array.
That is,

const_cast<int*>(&bar[0])

or, equivalently,

const_cast<int*>(bar)

Of course, this will only be valid if the C function doesn't ever modify the array.
If there is any risk of that, you should not make it const.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
2

If the C function was promising to not modify the data, then it would be taking a const void*. Since it doesn't, it might modify it. So don't make your array const:

class Foo
{
    static int bar[3];

    void method()
    {
        cfunction(bar);
    }
};

And define the array in the .cpp file of your class:

int Foo::bar[3] = {1, 2, 3};
Nikos C.
  • 50,738
  • 9
  • 71
  • 96