Search code examples
c++arraysstringcharmemcpy

What is the most efficient way to convert a string to a char array/ value that a char pointer can point to


If I have a string:

std::string Pooptacular = "Pooptacular"

and I want to convert it to a char array, I have some options one being:

char* poopCArr = Pooptacular.c_str();

or I can do something with memcpy or strcpy and such.

What I want to know is, which of these methods is the fastest or most efficient. In other words, which method should I use if I were to do this hundreds of thousands of times in one program run?


Solution

  • If you just need a read-only pointer to the data, use c_str. It doesn't convert anything. It just gives you access to the buffer string has already allocated. Of course, you have to copy it to a new buffer if you want to change it, and if you do, don't expect your changes to be reflected in your original string object.