in the c++ solution I am working on I have a function that returns a string reference. like const std::string& getData() const {return mData;}
and the mData is std::string mData;
. now I want to convert it to uint8_t
array to pass it to another function pointer.
/* in another header -> typedef uint8_t U8; */
const std::string& d = frame.getData();
U8 char_array[d.length()];
/* here I want to put the d char by char in char_array*/
the strcpy
is deprecated so I am using strcpy_s
like strcpy_s(char_array, d);
which of course I get couldn't match type char(&)[_size] against unsigned char[]
and also static or reinterpret casting to char*
does not work too.
Use a vector, what you are writing are VLAs, which is not valid C++ (U8 char_array[d.length()]
). then use std::copy
.
const std::string& d = frame.getData();
std::vector<U8> char_array(d.length() + 1, 0);
The question is if you need to have the end of string \0
or not, so it's going to be d.length()+1 if you want the last \0
. Then:
std::copy(std::begin(d), std::end(d), std::begin(char_array));
Update: Apparently, the goal is to store this vector in another uint8_t[8]
, if it's a variable named foo
, just do:
std::copy(std::begin(d), std::end(d), std::begin(foo));
But check the length first... And pass the structure to populate as a reference. Also get a good C++ book.