Copy const char* to uint8_t array

448 Views Asked by At

My C-API takes an array of uint8_t's as config parameter. I'm arriving at its doorsteps with a const char*. How do I now copy the chars over to the uint8_t array in the most unproblematic way? Here's what I've got (contrived ofc):

Demo

#include <cstdint>
#include <cstring>
#include <cstdio>

struct config
{
    uint8_t ssid_[32];
};


auto set_ssid(const char* ssid) {
    // I know this fn has no sideeffects but assume for demonstration
    // purposes that cfg is only initialized here
    config cfg;

    std::strncpy(static_cast<char*>(&cfg.ssid_), ssid, 32);
}

int main()
{
    set_ssid("ComeOver");
}

But this doesn't work as none of the pointer is of void* type:

<source>:14:18: error: invalid 'static_cast' from type 'uint8_t (*)[32]' {aka 'unsigned char (*)[32]'} to type 'char*'
   14 |     std::strncpy(static_cast<char*>(&cfg.ssid_), ssid, 32);
      |              

Is it safe to reinterpret_cast here?

1

There are 1 best solutions below

2
relent95 On

You should use cfg.ssid_ for the destination buffer instead of &cfg.ssid_. Also you should use reinterpret_cast instead of static_cast, because char * and unsigned char *(uint8_t *) are not pointer-interconvertible.(It's a rule refining various casts. See static_cast conversion.)

So this is recommended.

std::strncpy(reinterpret_cast<char*>(cfg.ssid_), ssid, 32);
// Or simply
std::strncpy((char *)(cfg.ssid_), ssid, 32);