9

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*)’
7
  • With ::memcpy() or with a cast to char*. Commented Feb 10, 2016 at 17:39
  • 1
    short answer: you shouldn't do it. user char array instead. Commented Feb 10, 2016 at 17:40
  • 1
    Why is this what you want to do? Commented Feb 10, 2016 at 17:42
  • @YSC: Thanks , im using c++, so please write the cast line in above case? Commented Feb 10, 2016 at 17:43
  • 1
    I know what you need to do, I don't know why you want to do it. Commented Feb 10, 2016 at 17:45

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

4 Comments

return is missing.
-.- I was mislead by the trailing return type... and by my lazyness: not to double check...
@ Cheers and hth. - Alf : Thanks a Lot !!
Just looking at this I realized that with a C++ implementation where std::string has raw pointers as iterators (unlikely but permitted), the unqualified call to copy would not invoke Argument Dependent Lookup and it would not be found. Fixed by adding namespace qualification.
2

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.