How to copy a std::string (sample) to unsigned char array (trap)?
int main() {
unsigned char trap[256];
std::string sample = ".1.3.6.1.4";
strcpy(trap,sample.c_str());
std::cout << trap << std::endl;
}
Above code throws error:
time.cpp: In function ‘int main()’:
time.cpp:20: error: invalid conversion from ‘unsigned char*’ to ‘char*’
time.cpp:20: error: initializing argument 1 of ‘char* strcpy(char*, const char*)’
Here's one way:
#include <algorithm>
#include <iostream>
auto main() -> int
{
unsigned char trap[256];
std::string sample = ".1.3.6.1.4";
std::copy( sample.begin(), sample.end(), trap );
trap[sample.length()] = 0;
std::cout << trap << std::endl;
}
It can be a good idea to additionally check whether the buffer is sufficiently large.
Using reinterpret_cast would also be possible:
int main() {
std::string sample = ".1.3.6.1.4";
auto uCharArr = reinterpret_cast<unsigned char*>(sample.c_str());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With