Reputation: 4563
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.
Upvotes: 0
Views: 4164
Reputation: 22023
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.
Upvotes: 4
Reputation: 5069
Update: Since it seems from your comments that you have a compile time constant maximum size, I added a true array version:
#include <string>
#include <vector>
#include <cstdint>
#include <algorithm>
#include <iterator>
#include <array>
struct foo {
std::string& getData() {return mData;}
const std::string& getData() const {return mData;}
std::vector<uint8_t> get_array() const {
std::vector<uint8_t> array;
std::copy(mData.cbegin(), mData.cend(), std::back_inserter(array));
return array;
};
static constexpr size_t max_size = 8u;
std::array<uint8_t, max_size> get_max_array() const {
std::array<uint8_t, max_size> array;
std::copy_n(mData.cbegin(), max_size, array.begin());
return array;
}
private:
std::string mData;
};
Upvotes: 0