1
votes

I need a bit of help with C++ syntax when using const void pointers.

I am passing a function a const void array (ie I don't know what data type it is). I then need to copy the block of memory byte by byte into a local unsigned char array (with and offset of 2).
The local array is declared outside the function & I know it will always be big enough. Here's the code:

void writeFram(const void* data, unsigned int startAddr, size_t size)
{
    i2cBuffer[0] = startAddr >> 8;
    i2cBuffer[1] = startAddr & 0xFF;
    for(unsigned char i=0;i<size;++i)
    {
        i2cBuffer[i+2] = *static_cast<unsigned char*>(data);
    }
}

The error I get is: error: static_cast from type 'const void*' to type 'unsigned char*' casts away qualifiers

2

2 Answers

2
votes

Don't cast constness away:

i2cBuffer[i+2] = *static_cast<const unsigned char*>(data)
//                            ^^^^^
0
votes

This is what const_cast is for. But you shouldn't use it. There's nothing wrong with casting to a const unsigned char *, because you're going to copy the value out.

Of course, you could also use memcpy.