I know the difference between:
char *a = "string";
char p[] = "string";
from *a
, it acts as the following...
+-----+ +---+---+---+---+---+---+---+
a: | *======> | s | t | r | i | n | g |\0 |
+-----+ +---+---+---+---+---+---+---+
If I want to create another variable say
char *b;
and I hope it copies all contents in pointer a points to instead of pointing to the a's content.
+-----+ +---+---+---+---+---+---+---+
a: | *======> | s | t | r | i | n | g |\0 |
+-----+ +---+---+---+---+---+---+---+
b: | *======> | s | t | r | i | n | g |\0 |
+-----+ +---+---+---+---+---+---+---+
How to do this ?
In C++, you can do
const size_t n = strlen(a); // excludes null terminator
char *b = new char[n + 1]{}; // {} zero initializes array
std::copy_n(a, n, b);
Live Example
However I recommend using std::string
over C-style string since it is
\0
-embedded strings correctlyIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With