I have a pointer, where the next X
elements are ASCII characters with a '\0'
at the end. I need to save the ASCII characters either in a char
array or string
type.
Is it possible to dynamically initialize a string
or char
array in C++
with a pointer? The code below does not compile with the following error:
char symbol[11];
symbol = (packet+8);
error: array type 'char [11]' is not assignable
( packet
is a pointer that holds the data and the ASCII characters start at the 8th location).
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:
char symbol[11];
std::copy(packet + 8, packet + 19, symbol);
or use a std::string
constructor:
std::string symbol(packet + 8, packet + 19);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.