Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a std::string to unsigned char array?

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*)’
like image 761
Ragav Avatar asked Feb 10 '16 17:02

Ragav


2 Answers

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.

like image 126
Cheers and hth. - Alf Avatar answered Sep 21 '22 23:09

Cheers and hth. - Alf


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());
}
like image 45
Jodo Avatar answered Sep 21 '22 23:09

Jodo