C ++ - 分配一个unsigned char缓冲区,然后用一个字符串填充它 [英] C++ - Allocate an unsigned char buffer and then fill it with a string

查看:462
本文介绍了C ++ - 分配一个unsigned char缓冲区,然后用一个字符串填充它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C ++ 非常新,所以请原谅我,如果这是一个天真的问题 - 但我坚持找到一个答案。



我试图创建一个 unsigned char 数组,大小 1024 具有以下代码:

  unsigned char * r_record = new unsigned char [1024] 

现在我有一个 std :: string 变量:

  std :: string hw =Hello Word; 

我想填充 r_record 10'字节开始的 hw (即Hello World
$ b

如何将 hw 放入 r_record



实际上,我的r_record数据看起来像('为空):



  [......... Hello World ......等等] 


解决方案

您可以使用 std :: copy $ c> header:

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

如果要使用向量而不是动态分配的数组/ p>

  std :: vector< unsigned char> r_record(1024); // 1024 zero initialized elements 
std :: copy(hw.begin(),hw.end(),r_record.begin()+ 10);


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]

解决方案

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

这篇关于C ++ - 分配一个unsigned char缓冲区,然后用一个字符串填充它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆