Re: string class :: how to get char* from a string object

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Jyotirmoy,

Here's a routine that produces a char* from a string:

char* charArray(std::string const& s)
{
  char* rv = new char[s.length()+1];
  strcpy(rv, s.c_str(), s.length()+1);
  return rv;
}

Note, you are responsible for doing the memory cleanup:
  char* p = charArray(s);
  delete[] p;

>Whether [casting away const] is a good option?

Not really.  You'd be better off ADDING const to those parts that are working with the char const*.

Stripping off the const is changing the contract, which the std::string doesn't necessarily support.  (Can vary from implementation to implementation.  What may work on platform XYZ may not work on platform ABC.)

NOTE:  manipulating characters through a char* (where the const has been stripped off) does NOT necessarily manipulate the characters in the underlying std::string!

>Whether string class will append a '\0' after storing the 'abcdef' or not ?

Not necessarily.  The std::string has a length specifier, akin to Pascal-style strings (but different in that the length isn't stored at the head of the character array).

>What will be the capacity of the above string object ?

Varies from implementation to implementation.

Use the std::string capacity() method to ascertain, on a case-by-case basis.

>Why it is not the same as no. of character of "abcdef" ?

The std::string makes a tradeoff between string manipulation efficiency and storage overhead.  The "slack" bytes are used to reduce the number of re-allocs during the life of the string.

Whether or not the capacity is the same as the number of characters of "abcdef" can be determined by the std::string capacity() method.

Stroustrup's C++ Programming Language 20.3 talks about std::string.

HTH,
--Eljay



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux