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/de-allocation (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:
const char* myCharPtr = "This is a string literal.";
Note the extra
const qualifier in there, this is because a string literal is saved in program memory and should not be written to.
As mentioned in the Overview, you can store characters (strings), in a type called string. To use this data type, you must #include
Converting To char*
You can get a
char* pointer to a string with the method
// Create a string type string myString("This is a string."); // Get a char* pointer to the string char* myCharPtr = myString.c_str(); // Now you can do C-like things with it like printf() printf("%s", myCharPtr);
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:
// Create new space for the char* on the heap myCharPtr = new char[myString.size() + 1]; // Copy the contents of the string into the newly allocated myCharPtr memcpy(myCharPtr, myString.c_str(), myString.size() + 1);