How to copy contents of the const char* type variable?

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

  • deals with \0-embedded strings correctly
  • safe
  • easy to use

In C, you can allocate a new buffer b, and then copy your string there with standard library functions like this:

b = malloc((strlen(a) + 1) * sizeof(char));
strcpy(b,a);

Note the +1 in the malloc to make room for the terminating '\0'. The sizeof(char) is redundant, but I use it for consistency.

In C++, you should use the safer and more elegant std::string:

std::string b {a};

Tags:

C++

C

Pointers