0

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?

kjh
  • 3,407
  • 8
  • 42
  • 79

1 Answers1

1

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.

acjay
  • 34,571
  • 6
  • 57
  • 100
  • Just what I needed. Muchas gracias – kjh Nov 21 '12 at 07:57
  • One more thing about this answer, when you ask to the pointer using `string::c_str` you're getting a pointer to **internal string data**, this breaks the encapsulation principle, it could be troublesome even if you rely on this pointer to perform read-only operations: what would happen if the `std::string` instance owner of the `const char *` is deleted?. IMHO is better to work with the `std::string` object instead of its `const char *` internal pointers btw: @kjh don't forget to mark the answer as accepted ;) – PaperBirdMaster Nov 21 '12 at 08:04