2

I am realively new to C++ so please forgive me if this is a naive question - but I'm stuck on finding an answer.

I am trying to create an unsigned char array of size 1024 which I have done with the following code:

unsigned char *r_record = new unsigned char[1024]();

Now I have an std::string variable:

std::string hw = "Hello Word";

And I would like to populate the r_record with hw (i.e., 'Hello World') starting at the 10'th byte.

How can I place hw into r_record?

So in effect, my r_record data would look like (where the .'s are empty):

[.........Hello World......and so on]
Brett
  • 10,971
  • 27
  • 114
  • 198
  • 1
    [**`std::copy(hw.begin(), hw.end(), r_record + 10);`**](http://en.cppreference.com/w/cpp/algorithm/copy) – 0x499602D2 Jan 26 '14 at 17:28
  • 1
    @0x499602D2: Why are you posting answers as bold comments? – Lightness Races in Orbit Jan 26 '14 at 17:55
  • 1
    You can't help being new, but you sure can help [using new](http://stackoverflow.com/questions/6500313/c-why-should-new-be-used-as-little-as-possible). If you don't want `std::string` for some reason, use `std::vector`. If this is homework, enlist in a better class. – TemplateRex Jan 26 '14 at 17:55
  • @LightnessRacesinOrbit Should I delete because I can't edit out the boldness?... – 0x499602D2 Jan 26 '14 at 18:03
  • @TemplateRex Since he needs `unsigned char`, it can't be `std::string` (at least not easily). But `std::vector` is definitely the right way to go. – James Kanze Jan 26 '14 at 18:41
  • @Everyone How would I use `std::vector` instead of `new unsigned char[1024]`? That came from another example. And no this isn't homework :-) Just me trying to expand my `Objective-C` knowledge into `C/C++`. – Brett Jan 26 '14 at 21:07

1 Answers1

8

You can use std::copy, from the algorithm header:

std::copy(hw.begin(), hw.end(), r_record + 10);

If you want to use a vector instead of the dynamically allocated array (a good idea), then

std::vector<unsigned char> r_record(1024); // 1024 zero initialized elements
std::copy(hw.begin(), hw.end(), r_record.begin() + 10);
juanchopanza
  • 210,243
  • 27
  • 363
  • 452
  • 2
    Just a quick note: that copies the characters (which is what he seems to be asking about); most binary formats (which is presumably why the buffer of `unsigned char`) also require some means of determining the length. (Also, of course, he should be using `std::vector`, and not `new unsigned char[]`.) – James Kanze Jan 26 '14 at 18:40