简体   繁体   English

用 C++ 中的指针初始化 char 数组或字符串

[英]Initialize a char array or string with a pointer in C++

I have a pointer, where the next X elements are ASCII characters with a '\0' at the end.我有一个指针,其中下一个X元素是ASCII字符,末尾有一个'\0' I need to save the ASCII characters either in a char array or string type.我需要将ASCII字符保存在char数组或string类型中。

Is it possible to dynamically initialize a string or char array in C++ with a pointer?是否可以使用指针动态初始化C++中的stringchar数组? The code below does not compile with the following error:下面的代码无法编译并出现以下错误:

char symbol[11];
symbol = (packet+8);

error: array type 'char [11]' is not assignable错误:数组类型“char [11]”不可分配

( packet is a pointer that holds the data and the ASCII characters start at the 8th location). packet是保存数据的指针, ASCII字符从第 8 个位置开始)。

Ideally, I would like to avoid having to iterate through the pointer to initialize the string or character array.理想情况下,我希望避免遍历指针来初始化字符串或字符数组。

for (int i = 0; i < 11; i++) {
    symbol[i] = *(packet+8+i);
}

Thank you in advance for all the help.预先感谢您的所有帮助。

You can use std::copy to copy the contents like this:您可以使用std::copy复制如下内容:

char symbol[11];
std::copy(packet + 8, packet + 19, symbol);

or use a std::string constructor:或使用std::string构造函数:

std::string symbol(packet + 8, packet + 19);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM