Strings

Overview

While strings are almost always represented as a pointer to a char or an array of characters in C (either char * or char[]), C++ introduces a std::string type. This offers the following advantages:

  • Automatic memory allocation/deallocation (no more buffer overruns!)
  • The size can be found by calling the appropriate method on the string object

However, this comes at a cost, now there is dynamic memory allocation. This may be a significant issue for embedded applications.

The Old C Style char*

The the most basic methods to store characters is to create a pointer to a character, e.g. char* myString. No standard library has to be included to be able to do this, and this is how you would typically store characters in C.

To actually store something (above, just a pointer was created, but assigned to nothing) you would commonly create a string literal, like this:

Note the extra const qualifier in there, this is because a string literal is saved in program memory and should not be written to.

Strings

As mentioned in the Overview, you can store characters (strings), in a type called string. To use this data type, you must #include <string>.

Converting To char*

You can get a char* pointer to a string with the method .c_str().

But be careful! Only read from this value, as writing to c_str() results in undefined behaviour! Also, there is no guarantee that your char* pointer will remain valid for any length of time. For example, if you appended more characters to the end, and the processor then had to move the entire string object in memory to get enough contiguous space, your char* pointer would become invalid.

If you wanted to get a copy which will last until your program ends, then instead you could copy the string into a char*, like this example:

Converting A Integer To A Hex String

See the String.hpp file in CppUtils repo.

Posted: January 9th, 2014 at 7:48 am
Last Updated on: August 15th, 2017 at 5:33 am