Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

pointers

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 ?

like image 426
Sam Avatar asked Oct 16 '14 08:10

Sam


1 Answers

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
like image 141
legends2k Avatar answered Sep 18 '22 07:09

legends2k