Dealing With Strings


This page is all about dealing with multiple characters; That is, what is commonly referred to as a string. Don’t get confused though, C++ has a type called string which is just one of the many ways you can deal with multiple characters.

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.


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 behvaiour! Also, there is no guarantee that your char* pointer will remain valid for any length of time. Say to used the original string type and appended more characters to the end. If the processor then had to go and move the entire variable in memory to get enough contegious 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: