0

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.

6
  • What is packet? Commented Jul 4, 2020 at 2:14
  • 1
    You can't assign a c-string. you can assign a std::string Commented Jul 4, 2020 at 2:14
  • 2
    std::string symbol = packet + 8; should work fine. Or if packet is not NUL-terminated, then std::string symbol(packet + 8, 11); Commented Jul 4, 2020 at 2:15
  • @KorelK packet is a const u_char*. Commented Jul 4, 2020 at 2:18
  • @IgorTandetnik I get the following error: no viable conversion from 'const u_char ' (aka 'const unsigned char *') to 'std::string' . Packet is of type const u_char Commented Jul 4, 2020 at 2:19

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

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.